I understand that standards before C++20 do not specifiy the representation of signed integers. Therefore, when left shifting a negative number, the result is undefined as it depends on the underlying representation. However, why when it comes to right shift, the behavior becomes implementation-defined instead of undefined? Doesn't the result still depend on the underlying representation?
In C++ for signed integers when on a left shift occurs and a sign bit 1 was shifted out, the behaviour is undefined.
0b000xyz << 3 == 0bxyz
0b001xyz << 3 is undefined
0b1xyz << 1 is undefined
For shift right the sign bit was repeatedly shifted in, the so called artithmetic bit shift. Except for -1 this is a division by 2 (-4 to -2 to -1, 4 to 2 to 1).
For the left shift one has for positive numbers this is a multiplication by 2 (1 to 2 to 4). But for negative numbers theoretically do -1 to -2 to -4 and it would behave (multiplication by 2), but if 0b10xyz << 3 happens there is a sign overflow and the choice 0b0xyz or 0b1xyz. In general a desirable behaviour cannot be found.
Hence a single test on the sign bit and then claiming "undefined" is a minimal checkable case.
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