user7851115
user7851115

Reputation:

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!

Upvotes: 5

Views: 1905

Answers (2)

user7851115
user7851115

Reputation:

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.)

Upvotes: 2

towi
towi

Reputation: 22267

g++ use C++11 by default for some time now.

Therefore you can use nullptr and be "modern" as well as type safe.

If you have to be pre-C++11 portable NULL is best.

Upvotes: 0

Related Questions