Let's say I have a C++ function that looks like this:
bool Foo(Bar* b)
{
if(b == nullptr) {
return false;
}
// Do stuff
return true;
}
Let's further say that, because of limitations with some of the tools I have that don't support any standards newer than C++03, I have this code in a header:
#if __cplusplus <= 199711L
#define nullptr (0)
#include <stdint.h>
#else
#include <cstdint>
#endif // End if C++03
My compiler will build this without warning or error. I know I don't have to cast nullptr but is there a compelling reason that I should do it? That is, is there the potential for some bug to creep in relative to to Foo() that using if (b == static_cast<Bar*>(nullptr)) would have avoided and that the compiler wouldn't have warned me about (in either C++03 or C++11 or later)?
My reasons for avoiding the cast would be:
- Adding the cast to every use of
nullptrseems like it would make the code more cluttered/harder to read. - I haven't seen much (if any) code that does so.
Number 2 isn't a good reason in and of itself, so I'm wondering if it's done because it's more convenient for the code author and/or if it's because there really is no compelling reason to do so.
Edit based on proposed answer: Questions are:
- If I'm stuck with C++03 now but still want to plan for C++11 in the future, is the best option to stick with legacy
NULLbeing set to an integer value and all the best-practices that come with it? - If I'm stuck with something of the
#define NULL (0)variety, should I always apply a cast? For example:if(b == static_cast<Bar*>(NULL))is not something I see done very much and I'm wondering if this is out of laziness or if there are good reasons to do or not do this in the case of comparisons (like null pointer checks exemplified above).
nullptrwhen you really meanNULL. If you have code that needs to compile on pre-C++11 compilers, then you should universally useNULL. Pretending thatnullptrandNULLare the same thing (as you're doing here) is a bad idea.NULLandnullptras interchangeable with0, even though there could be some obscure case where that fails. If it does, I'll just avoid that platform or library or whatever. :-D So I'd just doreturn b != 0;I get that it's less expressive and more ambiguous thanNULL, but dunno, I like plain old zero. Plus I worked in codebases where people treated NULL as zero for integer and boolean-related logic which was retarded, likeint x = NULL;which ruins the whole meaning of NULL anyway.