将unsigned int的移位量大于它的大小(未定义)? [英] Shifting unsigned int more than the size of it, undefined or not?

查看:93
本文介绍了将unsigned int的移位量大于它的大小(未定义)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2011年草稿说:

6.5.7按位移位运算符/4 E1的结果<< E2是E1左移E2位的位置;空位用零填充.如果E1具有无符号类型,则 结果的值是E1×2 ^ E2,比 结果类型中可表示的最大值.如果E1已签名 类型和非负值,并且E1×2E2在 结果类型,则为结果值;否则,行为 是未定义的.

6.5.7 Bitwise shift operators/4 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 × 2^E2, 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.

J.2未定义的行为:将表达式移位负数或大于或等于表达式宽度的量. 提升表达能力(6.5.7).

J.2 Undefined behavior An expression is shifted by a negative number or by an amount greater than or equal to the width of the promoted expression (6.5.7).

如何解释两者? J.2 是指所有班次(是否为未签名)还是在 6.5.7 部分中明确提到的UB(仅适用于已签名).

How to interpret both? Does J.2 refers to all shiftings (unsigned or not) or to the explicitly mentioned UB in section 6.5.7 (only for signed).

我的意思是,unsigned int i=...; i <<= sizeof(i)*CHAR_BIT; UB是吗?

I mean, is unsigned int i=...; i <<= sizeof(i)*CHAR_BIT; UB?

推荐答案

所引用的段落上方的段落表示相同的内容,而不管其签名如何:

The paragraph above the one you quoted says the same thing, regardless of the signedness:

6.5.7按位移位运算符/3 对每个操作数执行整数提升.结果的类型是 提升后的左操作数的值.如果右操作数的值为负或大于或等于提升的左操作数的宽度,则行为是不确定的.

6.5.7 Bitwise shift operators / 3 The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

因此,它是UB,无论是未签名还是已签名.

So, it's UB, whether it is unsigned or signed.

这篇关于将unsigned int的移位量大于它的大小(未定义)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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