I came across this piece of code from the Microsoft implementation of GSL (the C++ Guideline Support Library):
#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
I read about the __builtin_expect
(here and here), but it is still unclear to me what is the purpose of the double boolean negation operator in (!!(x))
. Why is it used?
The file in question is this one.
__builtin_expect
works with strict equality, so the point of double negation here is to make sure all truthy values are converted to 1 (and thus match the 1 in GSL_LIKELY
), and all the falsy values match the 0 in GSL_UNLIKELY
.
The double negation is kept even if __builtin_expect
is not available to keep uniformity (as the caller may store the return value for other uses besides as a condition in an if
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With