Large bitwise left shift on unsigned type

Sort of

uint32_t foo = 1;

foo = foo << 33;

undefined behavior in C?

+4
source share
2 answers

Offset is undefined behavior. See Standard (C11, final version N1570, 6.5.7p3):

"... If the value of the correct operand is negative or greater than or equal to the width of the advanced left operand, the behavior is undefined." .

Rationale: Shear operations can behave differently on different CPU architectures if the shift counter is> = argument width. Thus, the standard allows the compiler to generate the fastest code without worrying about border effects.

., , int 33 (, 64 ). - , uint32_t int, ( ) int. uint32_t , . 6.3.1.3, 1, 2 . int 32 .

+10

() undefined . C 6.5.7 ( WG14/N1256 - Septermber 7, 2007 ISO/IEC 9899: TC3 - C99):

  1. . - . , undefined.

  2. E1 < E2 - E1 E2; . E1 , E1 × 2 ^ E2, , , . E1 , E1 × 2 ^ E2 , ; undefined.

Re 3, , undefined, .

Re 4, , : E1 , E1 × 2 ^ E2, , . ( 3) , .

, 3 4, ( ) undefined.

, C11.

+4

Source: https://habr.com/ru/post/1616055/


All Articles