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
?
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:
- The language should impose no unnecessary overhead on the implementation.
- 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.
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