开发者

null pointer equivalence to int

In "The C++ Programming Language", Bjarne writes that the null pointer is not the same as the integer zero, bu开发者_JAVA百科t 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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜