Search code examples
c++nullcomparisonnull-pointernull-check

Null pointer check via "myPtr > 0"


In some legacy code I came across the following null pointer check.

if( myPtr > 0 ) {
...
}

Are there any technical risks of checking for a null pointer via this if-check?


Solution

  • Ordered comparison between a pointer and an integer is ill-formed in C++ (even when the integer is a null pointer constant such as it is in this case). The risk is that compilers are allowed to, and do, refuse to compile such code.


    You can rewrite it as either of these:

    if(myPtr != nullptr)
    if(myPtr)