c++undefined-behaviorbit-shift

Is left and right shifting negative integers defined behavior?


I know, right shifting a negative signed type depends on the implementation, but what if I perform a left shift? For example:

int i = -1;
i << 1;

Is this well-defined?

I think the standard doesn't say about negative value with signed type

if E1 has a signed type and non-negative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

It only clarifies that if the result isn't representable in signed type then the behavior is undefined.


Solution

  • You're not reading that sentence correctly. The standard defines it if: the left operand has a signed type and a non-negative value and the result is representable (and previously in the same paragraph defines it for unsigned types). In all other cases (notice the use of the semicolon in that sentence), i.e, if any of these conditions isn't verified, the behaviour is undefined.