Search code examples
c++98null-pointer

C++98 proper check for a null pointer


C++11 introduced the nullptr keyword, which I don't have available.

I suppose there is the NULL macro from C, which I read about using in C++ from some stuff here and here, but I'm still unsure what's the proper way of checking for a null pointer in this older standard of C++.

I essentially want to be able to write this code for my test case with Boost Test:

aWrapperDataStructure x;
BOOST_CHECK_NE(x.get_ptr(), static_cast<decltype(x.get_ptr())>(nullptr));

But maybe, as Tutorials Point suggested, something like this is more appropriate given the constraints:

BOOST_CHECK(x.get_ptr()); //true when not NULL

Something about that throws me off though, so I'm wondering what the best practice is here. If it's somewhere online, or on SO, it's been long buried and I can't find it. Thank you!


Solution

  • I don't feel right answering my own question here because I'm definitely not qualified to, but I read this answer here (It's still tagged C++ despite newer standards) from James Kanze:

    If you use g++, you really should use NULL.

    which is definitely good enough for me. I found these expressions for checking a null pointer though:

    (p != NULL) //requires #include <stddef.h>
    
    (p != 0)
    
    (p)
    

    And of these 3, the last one which I had mentioned in my question, does an implicit conversion from a pointer to a bool (hiss). Using != and == at least does an explicit conversion to a bool, and moreover, using NULL shows your intent of checking a null pointer.

    Therefore, I think even when not using g++, the expression (p != NULL) is the most appropriate way for the older C++ standard. (However, I'll still cede to someone else's expertise and mark their answer; I'm just an undergraduate student.)