开发者

null pointer equivalence to int

开发者 https://www.devze.com 2022-12-10 13:05 出处:网络
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. Doe

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

精彩评论

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