Is something like
uint32_t foo = 1;
foo = foo << 33;
undefined behaviour in C?
The shift is undefined behaviour in fact. See the standard (C11, final draft N1570, 6.5.7p3):
"... 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.".
Rationale: Shift operations can behave quite different on different CPU architectures if the shift count is >= the width of the argument. This way the standard allows the compiler to generate the fastest code without caring about border-effects.
Note: that things are different if int
is wider than 33 bits (e.g. 64 bits). Reason are the integer promotions which first convert the uint32_t
to int
, so the shift is executed with the (then larger) int
value. This leaves the back-conversion to uint32_t
of the assignment, See 6.3.1.3, paragraph 1, 2 for this case. However, on most modern systems, int
is not larger than 32 bits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With