c++cgccmacros

What is the purpose of a double negative in macro definition, like (!!(expr))?


Possible Duplicate:
Double Negation in C++ code.

I'm reading a code base, and find something like this:

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

I cannot figure out why (!!(expr)) is used instead of a single (expr). Anyway, a double negative means positive, is not it? Am I missing something?


Solution

  • It is a way to cast an expression to bool. In C++ though, operator! can be overloaded. Another way for C/C++:

    0 != (expr)
    

    C++ only way:

    static_cast<bool>(expr)
    

    [Edit] Thinking more about C++ operator overloading, it make sense to avoid using operators. Libraries like Boost.Spirit and Boost.Lambda use expression templates and lazy evaluation, so that expressions like (expr) || call() may behave not as expected. The most bullet proof version of that macro looks like this:

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

    Here, only conversion of expr to bool is used. The else branch is needed to protect from expressions like uassert(x) else something_else();.