Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting unsigned int more than the size of it, undefined or not?

Draft 2011 says:

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.

and

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

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

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

like image 667
Jean-Baptiste Yunès Avatar asked Aug 01 '17 08:08

Jean-Baptiste Yunès


1 Answers

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

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.

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

like image 61
Groo Avatar answered Oct 04 '22 21:10

Groo