Modern-CPP-Programming
Modern-CPP-Programming copied to clipboard
Inaccurate statement on bitwise operators on signed integers
Hello!
Firstly, I want to thank you for your large contribution to C++ community!
Unfortunately I have noticed an inaccurate statement in 04.Basic_Concepts_II.pdf, p.23. It states that
Bitwise operations on signed integer types is undefined behavior
int y = 1 << 12; // undefined behavior!!
However, that is not really true. In C++17, it the left operand is signed integer with negative value, the behavior is undefined. From C++17 Standard, 8.8, paragraph 2:
Otherwise, if E1 has a signed type and non-negative value, and E1 × 2 E2 is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.
In C++20, things are much easier. From C++20 Standard, 7.6.7, paragraph 2:
The value of E1 << E2 is the unique value congruent to E1 × 2 E2 modulo 2 N , where N is the width of the type of the result.
Could you please correct the slide, or tell me if I am wrong.
With best regards!