1<< 31产生错误,“<<'的结果,表达式未定义“ [英] 1 << 31 produces the error, "The result of the '<<' expression is undefined"

查看:157
本文介绍了1<< 31产生错误,“<<'的结果,表达式未定义“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在32位平台上将值声明为int类型并执行以下操作:

  int32_t mask; 
mask = 1<< 31://产生2147483648(或0x80000000)

有人可以帮助我理解上述行为什么会产生警告:

 '<<'表达式的结果未定义

int32_t ,它从-2 31 到(2 31 -1)。这是C11和C ++ 11中未定义的行为,并且在C ++ 14中实现定义。



C11§6.5.7/ p4(引用N1570) / p>


E1<< E2 E1 左移 E2
空位填充零。 [...]如果 E1 有签名类型
和非负值, E1×2 sup> E2
中表示为结果类型,那么结果值;


N3337中的C ++ 11规则§5.8[expr.shift] / p2几乎完全相同。因为2 31 不可表示,所以行为是未定义的。



C ++ 14§5.8[expr.shift] / p2 N3936;另见 CWG问题1457 ):


E1<< E2 E1 左移 E2
空闲位为零填充。 [...]否则,如果 E1 有一个签名的
类型和非负值, E1×2 E2 在结果类型的相应无符号类型中表示为
,那么
值,转换为结果类型,是结果值;
否则行为未定义。


As 2 31 位int,行为被定义,结果是2 31 转换为 int32_t ;这个转换是根据§4.7[conv.integral] / p3的实现定义。在一个使用二进制补码的典型系统中,你会得到-2 31


If I have value declared as of type int on a 32 bit platform and perform the following:

int32_t mask;
mask = 1 << 31: // produces 2147483648 (or 0x80000000)

Can someone help me understand why the above line would produce the warning:

The result of the '<<' expression is undefined

解决方案

231 isn't representable in a int32_t, which goes from -231 to (231-1). This is undefined behavior in C11 and C++11, and implementation-defined in C++14.

C11 §6.5.7/p4 (quoting N1570):

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. [...] 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.

The C++11 rule in N3337 §5.8 [expr.shift]/p2 is pretty much identical. Since 231 isn't representable, the behavior is undefined.

C++14 §5.8 [expr.shift]/p2 (quoting N3936; see also CWG issue 1457):

The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. [...] Otherwise, if E1 has a signed type and non-negative value, and E1×2E2is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.

As 231 is representable in an unsigned 32-bit int, the behavior is defined and the result is 231 converted to int32_t; this conversion is implementation-defined per §4.7 [conv.integral]/p3. In a typical system using two's complement you'd get -231.

这篇关于1&lt;&lt; 31产生错误,“&lt;&lt;'的结果,表达式未定义“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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