空指针等价于int [英] null pointer equivalence to int

查看:122
本文介绍了空指针等价于int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++编程语言中,Bjarne写道,空指针与整数零不同,但是0可以用作空指针的指针初始值。这是否意味着:

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


推荐答案

是的,这意味着 castPointer 不一定为零,并且断言可能失败。因为当空指针常数为零时,某种类型的空指针不一定是所有位为零的地址。

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 没有特殊规定在将空指针转换为int时产生零。你可以通过使用布尔运算符来实现,它将用 0 1

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

这篇关于空指针等价于int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆