双布尔否定运算符

Double boolean negation operator

我从 Microsoft implementation of GSL(C++ 指南支持库)中看到这段代码:

#if defined(__clang__) || defined(__GNUC__)
#define GSL_LIKELY(x) __builtin_expect(!!(x), 1)
#define GSL_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define GSL_LIKELY(x) (!!(x))
#define GSL_UNLIKELY(x) (!!(x))
#endif

我读到了 __builtin_expect (here and here),但我仍然不清楚 (!!(x)) 中的双重布尔否定运算符的目的是什么。为什么使用它?

有问题的文件是 this one

__builtin_expect 严格相等,所以这里双重否定的要点是确保所有真值都转换为 1(从而匹配 GSL_LIKELY 中的 1),并且所有虚假值匹配 GSL_UNLIKELY.

中的 0

即使 __builtin_expect 不可用以保持一致性,也会保留双重否定(因为调用者可以将 return 值存储为其他用途,除了作为 if 中的条件).