被右移未定义的行为,如果计数大于类型的宽度? [英] Is right shift undefined behavior if the count is larger than the width of the type?

查看:318
本文介绍了被右移未定义的行为,如果计数大于类型的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚检查了的 C ++ 的标准。看来下面code不应该未定义行为

I just checked the C++ standard. It seems the following code should NOT be undefined behavior:

unsigned int val = 0x0FFFFFFF;
unsigned int res = val >> 34;  // res should be 0 by C++ standard,
                               // but GCC gives warning and res is 67108863

和从标准:

E1 >> E2的值是E1右移E2位的位置。 如果E1
  有一个无符号类型,或者如果E1有一个签名的类型和一个非负
  值,则结果的值是的商的整数部分
  E1 / 2 ^ E2
如果E1有一个签名的类型和负值,将所得
  值是实现德网络定义。

The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

根据标准,因为34是不是负数,则变量 RES 将是0。

According to the standard, since 34 is NOT an negative number, the variable res will be 0.

GCC给出了code段以下警告和 RES 67108863

GCC gives the following warning for the code snippet, and res is 67108863:

警告:右移计数> =类型宽度

warning: right shift count >= width of type

我还检查了海湾合作委员会发出的组装code。它只是调用 SHRL ,并SHRL英特尔指导性文件,在 RES 不为零。

I also checked the assembly code emitted by GCC. It just calls SHRL, and the Intel instruction document for SHRL, the res is not ZERO.

这是否意味着GCC没有实现英特尔平台的标准行为?

So does that mean GCC doesn't implement the standard behavior on Intel platform?

推荐答案

在第C ++标准草稿 5.8 移位运算的段落中的 1 的说(强调雷的):

The draft C++ standard in section 5.8 Shift operators in paragraph 1 says(emphasis mine):

该结果的类型是,促进左操作数。 的行为是不确定如果有合适的操作数为负,或大于或等于促进左操作数的位长度

The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

所以,如果的 unsigned int类型的是 32位或更低,那么这是不确定这正是 GCC <警告/ code>是给你的。

So if unsigned int is 32 bits or less then this is undefined which is exactly the warning that gcc is giving you.

这篇关于被右移未定义的行为,如果计数大于类型的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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