Null: The never-ending story

Michał ‘mina86’ Nazarewicz | 27 marca 2011

I have already mentioned some problems with the null pointer but my recent discovery knocked my socks off.

By now, it should come with no surprise to anyone that 0 in pointer context acts as a null pointer (no matter of its actual representation). Moreover, it takes only a tiny bit of experimenting to figure out that expressions like (int)0 do as well. The latter is in itself a bit of a pita but it is conforming to the C++ standard which says:

4.10.1 A null pointer constant is an integral constant expression rvalue of integer type that evaluates to zero. […]

5.19.1 […] An integral constant-expression can involve only literals, enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions, non-type template parameters of integral or enumeration types, and sizeof expressions. […] Types bool, char, wchar_t, and the signed and unsigned integer types are collectively called integral types. A synonym for integral type is integer type. […]

Yes, not only (int)0 is a perfectly valid null pointer constant, but so are false, 1 - 1, sizeof(char) - sizeof(char), etc. Not only that, a const variable of type int with value of zero is also a valid null pointer constant.

This is not limited to C++ by the way. C has similar wording even though it treats fewer things as a constant expression. As a matter of fact, in the upcoming C++ standard it will become even worse as it adds more things to the definition of constant expression.

Like I’ve said, this comes to me as a bit of surprise and I have real trouble believing that it was C and C++ standard committees. Who could possibly want to represent a null pointer in a different way than plain 0 (or NULL (or nullptr)).

And now, a super important public service announcement: don’t feed the yao guai. Oh wait, wrong one. Beware of dereferencing a pointer cause you might assign null value to it instead of zeroing pointed to object.