请看下面的代码,为什么文字“1”没有积分提升?
long long n = 50;
long long a = 1 << n; // 262144
long long b = 1LL << n; // 1125899906842624
最佳答案
根据 elazar 的要求:
显示的结果是可接受的结果,因为移位调用未定义的行为。那是因为普通 1
是一个 int
,而移位一个int
由 0..(sizeof(int) * CHAR_BIT)-1
范围外的值(通常为 0..31
)导致到未定义的行为。
请注意,移位的类型仅受(提升的)左侧操作数的类型影响。这(如 chris 曾指出的那样)不同于大多数其他二元运算符,例如加法,其中两个操作数的类型会影响结果的类型。当然,赋值的类型由左操作数的类型控制,如果有必要,右侧的值会被强制转换为正确的类型(但赋值右侧的值是在不引用它所计算的类型的情况下计算的将被分配给,如本例所示)。
ISO/IEC 9899:2011 (C)
§6.5.7 Bitwise shift operators
¶3 The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
ISO/IEC 14822:2011(C++)
§5.8 Shift operators
The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand.
关于c++ - 带有左移运算符的奇怪积分促销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16880187/