为什么C ++编译器允许为指针分配0而没有其他数字 [英] Why C++ compiler allows assigning 0 to pointers and no other number
问题描述
我正在发布问题的答案-并发表评论,这要感谢另一个名为 metal 的海报
I was posting an answer to a question - and commenting it occured to me, thanks to another poster by the name metal that
C ++编译器允许以下操作:
C++ compiler allowed this:
int * p = 0;
不允许此 int * p = 1
。 0
被认为是一个特殊数字吗?
int *p = 0;
but not this int *p = 1
. Is 0
considered a special number?
编辑:@DavidHefferman说 0是否特殊?
-为什么?
@DavidHefferman said Is 0 special? In the context of a pointer, yes it is.
- why?
推荐答案
第4.10节标准,指针转换[conv.ptr]表示:
Section 4.10 of the standard, Pointer conversions [conv.ptr] says:
空指针常量是整数类型的整数常量表达式(5.19),计算结果为零
或std :: nullptr_t类型的prvalue。空指针常量可以转换为指针类型。结果
是该类型的空指针值,并且可以与指向对象的指针或指向函数类型的
指针的每个其他值区分开。这种转换称为空指针转换。
相同类型的两个空指针值应比较相等。空指针常量到cv限定类型的指针的转换是
一次转换,而不是指针转换后跟限定转换的序列(4.4)。
可以将整数类型的空指针常量转换为std :: nullptr_t类型的prvalue。
A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of pointer to object or pointer to function type. Such a conversion is called a null pointer conversion. Two null pointer values of the same type shall compare equal. The conversion of a null pointer constant to a pointer to cv-qualified type is a single conversion, and not the sequence of a pointer conversion followed by a qualification conversion (4.4). A null pointer constant of integral type can be converted to a prvalue of type std::nullptr_t.
所以,是的, 0
是指针上下文中的特殊值。
So, yes, 0
is a special value in the context of pointers.
这篇关于为什么C ++编译器允许为指针分配0而没有其他数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!