Search code examples
c++visual-c++conditional-statementscomparison-operators

How does `if ( __some_bool__ != NULL )` behave?


I was refactoring some code, when I came across some code that looked like this:

if( __some_bool__ != NULL ) {
    .....do something......
    }

Where __some_bool__ is a bool. I don't mean the BOOL that's typedef'd in the Windows headers.

This is most definitely NOT what (the programmer who wrote this) intended. But, before actually fixing it, I'd like to make sure I'm not breaking anything.

How will that evaluate? does false == NULL? What kind of coercion is going on?


Solution

  • NULL is usually defined as integer 0. And §4.7/4 from the C++ Standard says (Integral Conversion):

    If the source type is bool, the value false is converted to zero and the value true is converted to one.

    Conversion between bool and integer is implicit in C++. The rest is obvious. Typical programmer would replace this as simple:

    if( __some_bool__ ) {
        // do something
    }