C++ __builtin 函数常用用法、写法与拓展应用

· · 算法·理论

C++ __builtin 函数常用用法、写法与拓展应用

1. 什么是 __builtin

__builtin 通常指编译器内建函数,常见于 GCC 和 Clang。
它们不是 C++ 标准库的一部分,而是编译器直接提供的能力,通常用于:

这类函数的特点是:

2. 使用前的基本认识

2.1 头文件

大多数 __builtin_xxx 不需要额外头文件,编译器直接识别。
但某些配套能力可能仍会搭配这些头文件使用:

#include <iostream>
#include <cstdint>
#include <cstring>
using namespace std;

2.2 编译器兼容性

可以用条件编译做兼容:

#if defined(__GNUC__) || defined(__clang__)
    // 使用 __builtin
#endif

3. 最常用的位运算类 __builtin

这部分是算法、竞赛、底层开发里最常见的用法。

3.1 __builtin_popcount

作用

统计一个整数二进制表示中 1 的个数。

写法

int __builtin_popcount(unsigned int x);
int __builtin_popcountl(unsigned long x);
int __builtin_popcountll(unsigned long long x);

示例

unsigned int x = 13; // 1101
cout << __builtin_popcount(x) << endl; // 3

常见应用

拓展应用

// 判断是否是 2 的幂(x > 0)
bool isPowerOfTwo(unsigned int x) {
    return x && __builtin_popcount(x) == 1;
}

3.2 __builtin_parity

作用

判断二进制中 1 的个数是否为奇数。
返回值:

写法

int __builtin_parity(unsigned int x);
int __builtin_parityl(unsigned long x);
int __builtin_parityll(unsigned long long x);

示例

cout << __builtin_parity(7) << endl; // 7 = 111, 3 个 1,输出 1

拓展应用

3.3 __builtin_ctz

作用

统计从低位开始连续 0 的个数,即末尾 0 的数量。
ctz = count trailing zeros

写法

int __builtin_ctz(unsigned int x);
int __builtin_ctzl(unsigned long x);
int __builtin_ctzll(unsigned long long x);

示例

unsigned int x = 40; // 101000
cout << __builtin_ctz(x) << endl; // 3

重要注意

x = 0 时结果未定义。

安全写法:

int trailingZeros(unsigned int x) {
    return x ? __builtin_ctz(x) : 32;
}

拓展应用

1. 快速找到最低位的 1

int pos = __builtin_ctz(x); // 最低位 1 的下标

2. 提取 lowbit

unsigned int lowbit = x & -x;

也可结合 ctz 使用:

unsigned int lowbit = 1u << __builtin_ctz(x);

3. 状态压缩中遍历每一个置位 bit

for (unsigned int s = x; s; s &= (s - 1)) {
    int bit = __builtin_ctz(s);
    cout << bit << " ";
}

3.4 __builtin_clz

作用

统计从高位开始连续 0 的个数。
clz = count leading zeros

写法

int __builtin_clz(unsigned int x);
int __builtin_clzl(unsigned long x);
int __builtin_clzll(unsigned long long x);

示例

unsigned int x = 16; // 000...00010000
cout << __builtin_clz(x) << endl;

在 32 位 unsigned int 上,16 的前导零通常是 27。

重要注意

x = 0 时结果未定义。

拓展应用

1. 计算最高位 1 的位置

int highestBit(unsigned int x) {
    return x ? 31 - __builtin_clz(x) : -1;
}

2. 计算不小于 x 的最小 2 的幂

unsigned int ceilPow2(unsigned int x) {
    if (x <= 1) return 1;
    return 1u << (32 - __builtin_clz(x - 1));
}

3. 计算二进制位数

int bitWidth(unsigned int x) {
    return x ? 32 - __builtin_clz(x) : 0;
}

3.5 __builtin_ffs

作用

返回从低位到高位第一个 1 的位置,位置从 1 开始计数。
如果 x == 0,返回 0。

写法

int __builtin_ffs(int x);
int __builtin_ffsl(long x);
int __builtin_ffsll(long long x);

示例

cout << __builtin_ffs(40) << endl; // 40 = 101000,第一个 1 在第 4 位,输出 4

和 __builtin_ctz 的区别

关系:

if (x != 0) {
    __builtin_ffs(x) == __builtin_ctz(x) + 1;
}

4. 分支预测优化类

4.1 __builtin_expect

作用

告诉编译器某个条件“更可能”为真还是假,用于优化分支布局。

写法

long __builtin_expect(long expr, long expected);

示例

if (__builtin_expect(x == 0, 0)) {
    // 小概率事件
}

表示:x == 0 大概率为假。

常见宏写法:

#define LIKELY(x)   __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)

使用示例:

if (LIKELY(n > 0)) {
    // 常走路径
} else {
    // 冷门路径
}

拓展应用

注意

4.2 __builtin_unreachable

作用

告诉编译器这段代码理论上不可能执行到。

写法

void __builtin_unreachable(void);

示例

int f(int x) {
    if (x == 1) return 10;
    if (x == 2) return 20;
    __builtin_unreachable();
}

拓展应用

风险

如果程序实际跑到这里,行为未定义。
所以只能在你能严格证明“绝不可能到达”时使用。

5. 内存与性能优化类

5.1 __builtin_prefetch

作用

预取某段内存到缓存,降低未来访问延迟。

写法

void __builtin_prefetch(const void *addr, int rw = 0, int locality = 3);

参数含义:

示例

for (int i = 0; i < n; ++i) {
    __builtin_prefetch(&a[i + 16], 0, 1);
    sum += a[i];
}

拓展应用

注意

5.2 __builtin_memcpy / __builtin_memset

作用

编译器内建版本的内存操作,通常会被优化得更激进。

示例

char src[] = "hello";
char dst[10];
__builtin_memcpy(dst, src, 6);
int a[100];
__builtin_memset(a, 0, sizeof(a));

说明

很多时候直接写 memcpy、memset 即可,编译器本身就可能替换成内建实现。
手写 __builtin_memcpy 并不一定更优,更多出现在编译器相关代码或底层工程中。

6. 数学与浮点相关

6.1 __builtin_abs

作用

返回绝对值。

int x = -10;
cout << __builtin_abs(x) << endl; // 10

不过普通情况下直接使用 std::abs 更符合 C++ 风格。

6.2 __builtin_sqrt / __builtin_sin / __builtin_cos

一些数学函数存在内建版本,但业务代码里通常优先直接使用标准库:

#include <cmath>
cout << sqrt(25.0) << endl;

原因:

7. 类型与编译期判断类

7.1 __builtin_types_compatible_p

作用

判断两个类型是否兼容。这个更常见于 GNU C,C++ 中使用相对少。

写法

int __builtin_types_compatible_p(type1, type2);

示例

cout << __builtin_types_compatible_p(int, int) << endl;   // 1
cout << __builtin_types_compatible_p(int, long) << endl;  // 0

应用

在现代 C++ 中,很多场景更适合用:

7.2 __builtin_choose_expr

作用

根据编译期常量条件选择表达式。
更偏 GNU 扩展风格,C++ 里不如 if constexpr 常用。

示例

// GNU 扩展风格示意
// __builtin_choose_expr(cond, expr1, expr2)

现代 C++ 更推荐:

if constexpr (sizeof(T) == 4) {
    // ...
} else {
    // ...
}

8. 原子与并发相关

GCC 早期提供过一组原子内建函数:

后来又提供更现代的:

8.1 __sync_fetch_and_add

作用

原子加,并返回加之前的旧值。

示例

volatile int counter = 0;
int old = __sync_fetch_and_add(&counter, 1);

应用

8.2 __atomic_fetch_add

写法

type __atomic_fetch_add(type *ptr, type val, int memorder);

示例

int counter = 0;
int old = __atomic_fetch_add(&counter, 1, __ATOMIC_SEQ_CST);

常见内存序

说明

现代 C++ 项目中,更推荐优先考虑 std::atomic,因为:

但在底层库、运行时、编译器相关代码中,__atomic 仍很常见。

9. 栈与返回地址相关

9.1 __builtin_return_address

作用

获取当前函数调用者的返回地址。

示例

void* p = __builtin_return_address(0);

应用

注意

9.2 __builtin_frame_address

作用

获取当前栈帧地址。

void* p = __builtin_frame_address(0);

主要用于调试或底层运行时分析。

10. 实战场景总结

10.1 算法竞赛 / 位运算题

最常用:

示例:枚举集合中的所有元素下标

void printBits(unsigned int x) {
    while (x) {
        int i = __builtin_ctz(x);
        cout << i << " ";
        x &= (x - 1);
    }
}

10.2 高性能服务

常用:

示例:热路径优化

#define LIKELY(x)   __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)

int process(int x) {
    if (UNLIKELY(x < 0)) {
        return -1;
    }
    return x * 2;
}

10.3 底层并发编程

常用:

但如果不是在写底层库,优先考虑:

#include <atomic>
std::atomic<int> counter{0};
counter.fetch_add(1, std::memory_order_relaxed);

11. 常见坑点

11.1 对 0 使用 clz/ctz

以下行为未定义:

__builtin_ctz(0);
__builtin_clz(0);

使用前先判断:

if (x) {
    cout << __builtin_ctz(x) << endl;
}

11.2 搞错整数宽度

例如:

long long x;
__builtin_popcount(x); // 不严谨

更合适:

__builtin_popcountll(x);

应根据类型选择:

11.3 过度依赖编译器扩展

如果项目要求高可移植性,建议:

12. 推荐封装写法

为了可读性更好,可以做一层简单封装:

namespace bitutil {

inline int popcount(unsigned int x) {
    return __builtin_popcount(x);
}

inline int popcount(unsigned long long x) {
    return __builtin_popcountll(x);
}

inline int trailing_zero_count(unsigned int x) {
    return x ? __builtin_ctz(x) : 32;
}

inline int leading_zero_count(unsigned int x) {
    return x ? __builtin_clz(x) : 32;
}

inline int highest_bit(unsigned int x) {
    return x ? 31 - __builtin_clz(x) : -1;
}

}

使用时更清晰:

cout << bitutil::popcount(15u) << endl;
cout << bitutil::highest_bit(18u) << endl;

13. 与现代 C++ 标准库的对应关系

C++20 起,标准库已经提供了不少位操作工具,很多场景可以替代部分 __builtin:

#include <bit>

对应关系大致如下:

示例:

#include <bit>
#include <iostream>
using namespace std;

int main() {
    unsigned int x = 40;
    cout << std::popcount(x) << endl;
    cout << std::countr_zero(x) << endl;
    cout << std::countl_zero(x) << endl;
}

结论

如果你使用的是现代 C++(尤其 C++20 及以上):

14. 一份速查表

函数 作用 注意点
__builtin_popcount(x) 统计 1 的个数 注意类型宽度
__builtin_parity(x) 判断 1 的个数奇偶 返回 0/1
__builtin_ctz(x) 统计末尾 0 个数 x=0 未定义
__builtin_clz(x) 统计前导 0 个数 x=0 未定义
__builtin_ffs(x) 返回第一个 1 的位置 位置从 1 开始
__builtin_expect(x, v) 分支预测提示 只是提示
__builtin_unreachable() 标记不可达 到达则未定义
__builtin_prefetch(p) 预取内存 需实测收益
__sync_fetch_and_add 旧式原子加 老接口
__atomic_fetch_add 新式原子加 推荐胜过 __sync

15. 建议记住的高频结论

最值得优先掌握的是这几个:

  1. __builtin_popcount(x):数二进制中有多少个 1
  2. __builtin_ctz(x):找最低位 1
  3. __builtin_clz(x):找最高位 1
  4. __builtin_expect(x, v):分支预测提示
  5. __builtin_prefetch(p):缓存预取

如果你是:

16. 附:一个综合示例

#include <bit>
#include <iostream>
using namespace std;

#define LIKELY(x)   __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)

int main() {
    unsigned int x = 44; // 101100

    cout << "popcount = " << __builtin_popcount(x) << '\n';
    cout << "trailing zeros = " << __builtin_ctz(x) << '\n';
    cout << "leading zeros = " << __builtin_clz(x) << '\n';
    cout << "first set bit position = " << __builtin_ffs(x) << '\n';

    if (LIKELY(x > 0)) {
        cout << "highest bit index = " << 31 - __builtin_clz(x) << '\n';
    }

    cout << "std::popcount = " << std::popcount(x) << '\n';
    return 0;
}

17. 最后总结

__builtin 是 C++ 中非常实用的一组编译器扩展,尤其适合:

但使用原则应当是:

本篇文章全部内容均由chatGPT生成