null pointer equivalence to int

2019-05-17 00:46发布

问题:

In "The C++ Programming Language", Bjarne writes that the null pointer is not the same as the integer zero, but instead 0 can be used as an pointer initializer for a 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

回答1:

Yes, that means that castPointer isn't necessarily zero, and the assert may fail. Because while the null pointer constant is zero, the null pointer of some type is not necessarily an address with all bits zero.

reinterpret_cast has no special provisions to yield zero when casting a null pointer to int. You can achieve that by using boolean operators, which will initialize the variable with either 0 or 1:

int castPointer = (voidPointer != 0);