Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double boolean negation operator [duplicate]

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.

like image 508
Nick Avatar asked Feb 17 '18 10:02

Nick


1 Answers

__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).

like image 179
Matteo Italia Avatar answered Nov 03 '22 14:11

Matteo Italia