Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Large bitwise left shift on unsigned type

Tags:

c

Is something like

uint32_t foo = 1;

foo = foo << 33;

undefined behaviour in C?

like image 387
P45 Imminent Avatar asked Dec 09 '22 00:12

P45 Imminent


1 Answers

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.

like image 54
too honest for this site Avatar answered Jan 04 '23 16:01

too honest for this site