Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitshift and integer promotion?

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; 

etc.

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; 

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 

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

like image 623
R.. GitHub STOP HELPING ICE Avatar asked Aug 14 '10 06:08

R.. GitHub STOP HELPING ICE


People also ask

What is a Bitshift operation?

Bit shifting is an operation done on all the bits of a binary value in which they are moved by a determined number of places to either the left or right. Bit shifting is used when the operand is being used as a series of bits rather than as a whole.

What is bit shifting in C++?

The right-shift operator causes the bit pattern in shift-expression to be shifted to the right by the number of positions specified by additive-expression. For unsigned numbers, the bit positions that have been vacated by the shift operation are zero-filled.


1 Answers

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 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.

like image 132
mark4o Avatar answered Oct 03 '22 22:10

mark4o