Bitshift 和整数提升? [英] Bitshift and integer promotion?

查看:19
本文介绍了Bitshift 和整数提升?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,C 要求二元运算符的操作数提升为更高级别操作数的类型.这可以用来避免使用冗长的强制转换填充代码,例如:

Normally, C requires that a binary operator's operands are promoted to the type of the higher-ranking operand. This can be exploited to avoid filling code with verbose casts, for example:

if (x-48U<10) ...
y = x+0ULL << 40;

但是,我发现,至少对于 gcc,这种行为不适用于位移位.即

However, I've found that, at least with gcc, this behavior does not work for bitshifts. I.e.

int x = 1;
unsigned long long y = x << 32ULL;

我希望右手操作数的类型导致左手操作数被提升为 unsigned long long 以便转换成功.但相反,gcc 会打印警告:

I would expect the type of the right-hand operand to cause the left-hand operand to be promoted to unsigned long long so that the shift succeeds. But instead, gcc prints a warning:

warning: left shift count >= width of type

gcc 是否被破坏了,或者标准是否对位移位的类型提升规则做了一些例外?

Is gcc broken, or does the standard make some exception to the type promotion rules for bitshifts?

推荐答案

所谓的通常的算术转换适用于许多二元运算符,但不是全部.例如,它们不适用于位移运算符、&&、||、逗号运算符和赋值运算符.这是位移运算符的规则:

The so-called usual arithmetic conversions apply to many binary operators, but not all of them. For example they do not apply to the bit shift operators, &&, ||, comma operator, and assignment operators. This is the rule for the bit shift operators:

6.5.7 ... 3 个语义 ...
对每个操作数执行整数提升.结果的类型是提升的左操作数的类型.如果右操作数的值为负或大于或等于提升的左操作数的宽度,则行为未定义.

6.5.7 ... 3 Semantics ...
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.

这篇关于Bitshift 和整数提升?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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