5

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!

  • I made a mistake in my `nullptr` example. Correcting it as per the example I saw here: https://stackoverflow.com/questions/37673724/boost-test-check-whether-a-pointer-is-null, which also more or less answered my question entirely. –  Jul 05 '17 at 13:47

2 Answers2

2

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

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • 2
    It's the style equivalent of a micro-optimisation question. How you test for null is highly unlikely to make any difference to the readability of your code, and you see all methods in production C++. – Malcolm McLean Jul 05 '17 at 14:39
  • Yes, but I can't tell you how many times my code wouldn't compile because of this stupid issue. Even something like `BOOST_CHECK_NE(p, NULL);` wasn't allowed because "ISO C++ forbids comparison between pointer and integer". Yet, `BOOST_CHECK(p != NULL)` is perfectly valid. –  Jul 05 '17 at 14:42
  • Ah. Just had to cast `NULL` to the right pointer type. I'm still new to this :) –  Jul 05 '17 at 14:53
0

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.

towi
  • 21,587
  • 28
  • 106
  • 187