先上代码
11 #include <stdio.h>
12
13 #define likely(x) __builtin_expect(!!(x), 1)
14 #define unlikely(x) __builtin_expect(!!(x), 0)
15
16 int main(int argc, const char* argv[]) {
17 int count = 10;
18 if (likely(count > 1))
19 printf("It is ok\n");
20 else
21 printf("It isn't ok\n");
22
23 int tmp = !!5;
24 printf("tmp = %d\n", tmp);
25
26 tmp = !!0;
27 printf("tmp = %d\n", tmp);
28 return 0;
29 }
再上输出结果
It is ok
tmp = 1
tmp = 0
结论
1 __builtin_expect是gcc提供的,目的是为了优化代码
2 __builtin_expect(Exp, N),意思是Exp == N的概率很大
3 !!的写法,是为了确保最后表达式的值 = 0 or 1