Double boolean negation operator

I came across this piece of code from Microsoft on the implementation of GSL (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 __builtin_expect ( here and here ), but it is still unclear what the purpose of the double Boolean negation operator in (!!(x)) . Why is it used?

This file is this .

+5
source share
1 answer

__builtin_expect works with strict equality, so the double negation point here is to make sure that all right values ​​are converted to 1 (and thus correspond to 1 in GSL_LIKELY ), and all false values ​​correspond to 0 in GSL_UNLIKELY .

Double negation persists even if __builtin_expect not available to maintain uniformity (since the caller can store the return value for other purposes, except as a condition in if ).

+6
source

Source: https://habr.com/ru/post/1275415/


All Articles