为什么-1 >大小(整数)?
考虑以下代码:
template<bool> class StaticAssert;
template<> class StaticAssert<true> {};
StaticAssert< (-1 < sizeof(int)) > xyz1; // Compile error
StaticAssert< (-1 > sizeof(int)) > xyz2; // OK
为什么是 -1 >sizeof(int)
是吗?
-1
是不是真的提升为unsigned(-1)
然后unsigned(-1)>sizeof(int)
.-1 > 是真的吗?sizeof(int)
等价于-1 >size_t(4)
如果 sizeof(int) 是 4.如果是这样,为什么-1 >size_t(4)
是假的?
- Is it true that
-1
is promoted tounsigned(-1)
and thenunsigned(-1) > sizeof(int)
. - Is it true that
-1 > sizeof(int)
is equivalent to-1 > size_t(4)
if sizeof(int) is 4. If this is so why-1 > size_t(4)
is false?
这是符合 C++ 标准的吗?
推荐答案
以下是标准(ISO 14882)如何解释 abort -1 > sizeof(int)
The following is how standard (ISO 14882) explains abort -1 > sizeof(int)
关系运算符 `>' 在 5.9 (expr.rel/2) 中定义
Relational operator `>' is defined in 5.9 (expr.rel/2)
通常的算术转换是在算术操作数上执行或枚举类型....
The usual arithmetic conversions are performed on operands of arithmetic or enumeration type. ...
常用的算术转换定义在 5 (expr/9)
The usual arithmetic conversions is defined in 5 (expr/9)
...该模式称为通常的算术转换,定义如下:
... The pattern is called the usual arithmetic conversions, which are defined as following:
- 如果任一操作数的类型为 long双倍,...
- 否则,如果任一操作数是双精度的,...
- 否则,如果任一操作数为浮点数,...
- 否则,应在两个操作数上执行整数提升.
- ...
积分促销在 4.5 (conv.prom/1) 中定义
The integral promotions is defined in 4.5 (conv.prom/1)
char 类型的右值,带符号的 char,unsigned char、short int 或 unsignedshort int 可以转换为如果 int 可以,则为 int 类型的右值表示源的所有值类型;否则,源右值可以被转换为类型的右值无符号整数.
An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.
sizeof的结果定义在5.3.3 (expr.sizeof/6)
The result of sizeof is defined in 5.3.3 (expr.sizeof/6)
结果是一个类型的常量尺寸_t
The result is a constant of type size_t
size_t 是在 C 标准 (ISO 9899) 中定义的,它是无符号整数类型.
size_t is defined in C standard (ISO 9899), which is unsigned integer type.
所以对于 -1 >sizeof(int)
,> 触发通常的算术转换.通常的算术转换将 -1 转换为 unsigned int,因为 int 不能表示 size_t
的所有值.-1
成为一个非常大的数字,取决于平台.所以 -1 >sizeof(int)
是 true
.
So for -1 > sizeof(int)
, the > triggers usual arithmetic conversions. The usual arithmetic conversion converts -1 to unsigned int because int cannot represent all the value of size_t
. -1
becomes a very large number depend on platform. So -1 > sizeof(int)
is true
.
相关文章