c++ - 带有左移运算符的奇怪积分促销

标签 c++ c type-conversion

请看下面的代码,为什么文字“1”没有积分提升?

long long n = 50;
long long a = 1 << n; // 262144
long long b = 1LL << n; // 1125899906842624

最佳答案

根据 elazar 的要求:

显示的结果是可接受的结果,因为移位调用未定义的行为。那是因为普通 1 是一个 int,而移位一个int0..(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/

相关文章:

android - Eclipse中未定义的外部引用

c - 无法处理从 cc3200 launchpad 到本地服务器或 http 服务器的 http post、get、put 和删除请求

c - Malloc 调用崩溃,但在其他地方工作

无法使用 lseek 在文件末尾添加空格

c++ - 如何使用c标准库获取目录大小

c++ - 从重载函数 std::real<float> 解析地址

type-conversion - 如何将 int[] 转换为 uint8[]

rust - 如何向现有原始类型添​​加构造函数?

Java:为什么我会收到错误消息 "Type mismatch: cannot convert int to byte"

c++ - 如何使用asm intel语法从c中的asm访问char?