问题描述
如果我在32位平台上将值声明为int类型并执行以下操作:
int32_t mask;
mask = 1<< 31://产生2147483648(或0x80000000)
有人可以帮助我理解上述行为什么会产生警告:
'<<'表达式的结果未定义
int32_t ,它从-2 到(2 -1)。这是C11和C ++ 11中未定义的行为,并且在C ++ 14中实现定义。
C11§6.5.7/ p4(引用N1570) / p>
N3337中的C ++ 11规则§5.8[expr.shift] / p2几乎完全相同。因为2 不可表示,所以行为是未定义的。
C ++ 14§5.8[expr.shift] / p2 N3936;另见):
As 2 位int,行为被定义,结果是2 转换为
int32_t
;这个转换是根据§4.7[conv.integral] / p3的实现定义。在一个使用二进制补码的典型系统中,你会得到-2 。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
解决方案2 isn't representable in a
int32_t
, which goes from -2 to (2-1). This is undefined behavior in C11 and C++11, and implementation-defined in C++14.C11 §6.5.7/p4 (quoting N1570):
The C++11 rule in N3337 §5.8 [expr.shift]/p2 is pretty much identical. Since 2 isn't representable, the behavior is undefined.
C++14 §5.8 [expr.shift]/p2 (quoting N3936; see also CWG issue 1457):
As 2 is representable in an unsigned 32-bit int, the behavior is defined and the result is 2 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 -2.这篇关于1<< 31产生错误,“<<'的结果,表达式未定义“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!