I know that the following code in C:
(1 << 31)
is considered Undefined Behavior due to the C standard (6.5.3 Shift Operators):
The result of the shift operation is undefined if the right operand is negative or if its value is greater than the number of bits in an int.
I’m just curious whether following C code:
(1LL << 63)
is also considered Undefined Behavior in any of the C standards.
C23 Section 6.5.7 says (my emphasis):
The result of
E1 << E2
isE1
left-shiftedE2
bit positions; vacated bits are filled with zeros. IfE1
has an unsigned type, the value of the result isE1
×2ᴱ²
, wrapped around. IfE1
has a signed type and nonnegative value, andE1
×2ᴱ²
is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
So if your platform's long long
can represent 2⁶³, you're fine. Since one bit must be used to indicate its sign, that means 1LL << 63
is UB if long long
has 64 bits.
(long long
cannot be smaller than 64 bits, but may be wider).