是1<<当sizeof(int)== 4时在C中定义了31 [英] Is 1 << 31 well defined in C when sizeof(int) == 4
问题描述
根据
E1的结果<< E2 是 E1 左移的 E2 位位置;空位用零填充.如果 E1 具有无符号类型,则结果的值为 E1×2 E2 ,比以结果类型.如果 E1 具有带符号的类型且非负值,并且 E1×2 E2 可表示为结果类型,则为结果值;否则,行为是不确定的.
The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined. 似乎暗示 但是,如果我使用 However GCC doesn't issue a warning if I use 那是什么?我误会了标准吗?
GCC有自己的解释吗? So which is it? Am I misunderstanding the standard?
Does GCC have its own interpretation? 否:如果类型 No: 在字节具有8位的系统上, On a system where bytes have 8 bits, 要解决米歇尔·罗伊(MichaëlRoy)的评论, To address Michaël Roy's comments, 例如,以下代码可能会编译为简单的 For example, the following code might compile to a simple Godbolt的编译器资源管理器不支持,但是这样做不会破坏一致性. None of the compilers supported by Godbolt's compiler explorer do, but doing so would not break conformity. 这篇关于是1<<当sizeof(int)== 4时在C中定义了31的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
1 << 31
未定义.1 << 31
,则GCC不会发出警告.
它确实为1 << 32
发出一个.
链接 1 << 31
.
It does issue one for 1 << 32
.
link推荐答案
int
仅具有31个值位,则1 << 31
具有未定义的行为.1 << 31
has undefined behavior if the type int
has only 31 value bits.1U << 31
正常,并且如果类型unsigned int
具有32个值位,则求值为0x80000000
.1U << 31
is OK and evaluates to 0x80000000
if type unsigned int
has 32 value bits.sizeof(int) == 4
表示int
最多具有31个值位,因此未定义将1移位31位.相反,在CHAR_BIT > 8
的系统上,可以写1 << 31
.sizeof(int) == 4
means int
has at most 31 value bits, so shifting 1 by 31 places is undefined. Conversely, on a system where CHAR_BIT > 8
, it may be OK to write 1 << 31
.gcc
可能会发出警告.尝试gcc -Wall -Wextra -W -Werror
. clang
确实发出带有相同选项的警告.gcc
might issue a warning if you raise the warning level. try gcc -Wall -Wextra -W -Werror
. clang
does issue a warning with the same options.1 << 31
不会不可靠地评估为INT_MIN
.它可能会在您的系统上提供此值,但标准并不能保证该值,实际上,该标准将其描述为未定义的行为,因此,不仅不能不依赖它,还应避免使用它以避免虚假错误.优化器通常利用潜在的未定义行为来删除代码并破坏程序员的假设.1 << 31
does not evaluate to INT_MIN
reliably. It might give this value on your system, but the Standard does not guarantee it, in fact the Standard describes this as undefined behavior, so not only can you not rely on it, you should avoid it to avoid spurious bugs. The optimizers routinely take advantage of potential undefined behavior to remove code and break the programmers' assumptions.return 1;
:return 1;
:int check_shift(int i) {
if ((1 << i) > 0)
return 1;
else
return 0;
}