Undefined right shift behavior (a >> b) when b is greater than the number of bits in a?

Apparently the behavior of the right shift operation is:

a >> b

is undefined in C and C ++ when b >= sizeof(a)*CHAR_BIT(whereas in the normal case the "new bits" entered on the left due to the right shift are equal to zero).

Why is this undefined behavior better than setting the result to zero when b >= sizeof(a)*CHAR_BIT?

+4
source share
2 answers

We can understand why languages ​​choose undefined behavior from Why language designers are Tolerate undefined Behavior and he says:

C:

  • .
  • C .

, , , , , , ::/p >

5 bits, , x86 Intel® 64 IA- 32 SAL/SAR/SHL/SHR-Shift IA-32 :

8086 . , IA-32 ( Intel 286) 5 , 31. [...]

, , undefined.

-C, :

. , , , "" , undefined .

, - , .

+6

, undefined , .

CPU , . , . , , .

// Example - not specified behavior  (assume 32-bit int)
y = 1 << 34;
// same as 
y = 1 << 2;

8/16 -, 8 , , , `int width, 256. , 1 . , shift 255 . , 16 , , 0, . ! , , . Intel .

+3

All Articles