Equivalence of a null pointer to int

In the "C ++ programming language" Bjarne writes that the null pointer does not match the zero number, but instead 0 can be used as a pointer initializer for the null pointer. Does this mean that:

void * voidPointer = 0; int zero = 0; int castPointer = reinterpret_cast<int>(voidPointer); assert(zero == castPointer) // this isn't necessarily true 
+3
c ++ null pointers
source share
1 answer

Yes, that means castPointer not necessarily zero, and the statement may fail. Since while the null pointer constant is zero, a null pointer of some type is not necessarily an address with all bits of zero.

reinterpret_cast has no special provisions for getting zero when casting a null pointer to an int. You can achieve this using logical operators that initialize the variable with 0 or 1 :

 int castPointer = (voidPointer != 0); 
+5
source share

All Articles