Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Before C++ 20, when the left operand is negative, why left shift is undefined behavior but right shift is implementation defined?

Tags:

c++

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?

like image 808
user18676624 Avatar asked Nov 01 '25 14:11

user18676624


1 Answers

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.

like image 65
Joop Eggen Avatar answered Nov 03 '25 06:11

Joop Eggen