是1<<当sizeof(int)== 4时在C中定义了31 [英] Is 1 << 31 well defined in C when sizeof(int) == 4

查看:213
本文介绍了是1<<当sizeof(int)== 4时在C中定义了31的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据

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.

似乎暗示1 << 31未定义.

但是,如果我使用1 << 31,则GCC不会发出警告. 它确实为1 << 32发出一个. 链接

However GCC doesn't issue a warning if I use 1 << 31. It does issue one for 1 << 32. link

那是什么?我误会了标准吗? GCC有自己的解释吗?

So which is it? Am I misunderstanding the standard? Does GCC have its own interpretation?

推荐答案

否:如果类型int仅具有31个值位,则1 << 31具有未定义的行为.

No: 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.

在字节具有8位的系统上,sizeof(int) == 4表示int最多具有31个值位,因此未定义将1移位31位.相反,在CHAR_BIT > 8的系统上,可以写1 << 31.

On a system where bytes have 8 bits, 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.

要解决米歇尔·罗伊(MichaëlRoy)的评论,1 << 31不会可靠地评估为INT_MIN.它可能会在您的系统上提供此值,但标准并不能保证该值,实际上,该标准将其描述为未定义的行为,因此,不仅不能不依赖它,还应避免使用它以避免虚假错误.优化器通常利用潜在的未定义行为来删除代码并破坏程序员的假设.

To address Michaël Roy's comments, 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;:

For example, the following code might compile to a simple return 1;:

int check_shift(int i) {
   if ((1 << i) > 0)
       return 1;
   else
       return 0;
}

Godbolt的编译器资源管理器不支持,但是这样做不会破坏一致性.

None of the compilers supported by Godbolt's compiler explorer do, but doing so would not break conformity.

这篇关于是1&lt;&lt;当sizeof(int)== 4时在C中定义了31的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆