gpt4 book ai didi

c++ - 如果计数大于类型的宽度,是否右移未定义行为?

转载 作者:IT老高 更新时间:2023-10-28 12:38:56 25 4
gpt4 key购买 nike

我刚刚检查了 C++ 标准。看来下面的代码不应该是 undefined behavior :

unsigned int val = 0x0FFFFFFF;
unsigned int res = val >> 34; // res should be 0 by C++ standard,
// but GCC gives warning and res is 67108863

从标准来看:

The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

根据标准,由于34不是负数,变量res将为0。

GCC对代码片段给出以下警告,res67108863:

warning: right shift count >= width of type

我还检查了 GCC 发出的汇编代码。它只是调用SHRL,而英特尔的SHRL指令文档中,res不是零。

那么这是否意味着 GCC 没有在英特尔平台上实现标准行为?

最佳答案

draft C++ standard在第 5.8 部分 Shift 运算符 在第 1 段中说(强调我的):

The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

所以如果 unsigned int32 bits 或更少,那么这是未定义的,这正是 gcc 给你的警告。

关于c++ - 如果计数大于类型的宽度,是否右移未定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18918256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com