Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Apparently, the behaviour of the right shift operation:

a >> b

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

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

like image 530
Vincent Avatar asked Jan 08 '23 17:01

Vincent


1 Answers

We can get an idea of why languages choose undefined behavior from Why Language Designers Tolerate Undefined Behavior and it says:

This answer came from two general design principles behind C:

  1. The language should impose no unnecessary overhead on the implementation.
  2. It should be as easy as possible to implement C on a wide variety of hardware.

in this specific case what happens when we use a shift count larger than the bit width will depend on the architecture for example as I explain in my answer here:

on some platforms the shift count will be masked to 5 bits for example on an x86 architecture we can see the Intel® 64 and IA-32 Architectures Software Developer’s Manual section SAL/SAR/SHL/SHR—Shift in the IA-32 Architecture Compatibility section says:

The 8086 does not mask the shift count. However, all other IA-32 processors (starting with the Intel 286 processor) do mask the shift count to 5 bits, resulting in a maximum count of 31. [...]

So implementing shift for an arbitrary count may be burdensome on some platforms and therefore it is better to leave it undefined behavior.

Why not unspecified behavior

If we look at the Rationale for International Standard—Programming Languages—C it says:

Unspecified behavior gives the implementor some latitude in translating programs. This latitude does not extend as far as failing to translate the program, however, because all possible behaviors are “correct” in the sense that they don’t cause undefined behavior in any implementation.

So there must have been a case or still exists a case where the behavior is not correct and would have bad issues.

like image 121
Shafik Yaghmour Avatar answered Jan 15 '23 10:01

Shafik Yaghmour