What is the purpose of double negation in the definition of a macro, for example (!! (expr))?

Possible duplicate:
Double negation in C ++ code.

I read the code base and find something like this:

#define uassert(msgid, msg, expr) (void)((!!(expr))||(uasserted(msgid, msg), 0)) 

I cannot understand why (!! (expr)) is used instead of one (expr) . Anyway, double negative means positive, right? Did I miss something?

+7
source share
4 answers

This is a way to express an expression for bool. In C ++, though, the operator! may be overloaded. Another way for C / C ++:

 0 != (expr) 

C ++ only:

 static_cast<bool>(expr) 

[edit] Thinking more about overloading the C ++ operator, it makes sense to avoid using operators. Libraries like Boost.Spirit and Boost.Lambda use expression patterns and lazy evaluation, so expressions like (expr) || call() (expr) || call() may not behave as expected. The most bulletproof version of this macro is as follows:

 #define uassert(expr) if(expr) {} else { uasserted(...); } 

Only the conversion of expr to bool is used here. The else branch is needed to protect against expressions like uassert(x) else something_else(); .

+6
source

He just makes sure that the expr part of the macro is converted to bool.

+1
source

This is an idiom sometimes used in C ++ to convert to a boolean type.

+1
source

In the example you showed us !! completely useless. However, in general, it was used as a preliminary C99 rough equivalent for casting on _Bool , i.e. 0 remains 0, and any other value becomes equal to 1.

0
source

All Articles