Is left-shifting (<<) a negative integer undefined behavior in C++11?
Yes, I would say it's undefined. If we translate the standardese to pseudo-code:
if (typeof(E1) == unsigned integral)
value = E1 * 2^E2 % blah blah;
else if (typeof(E1) == signed integral && E1 >= 0 && representable(E1 * 2^E2))
value = E1 * 2^E2;
else
value = undefined;
I'd say the reason why they're explicit about the right-hand operand and not about the left-hand one is that the paragrpah you quote (the one with the right-hand operand case) applies to both left and right shifts.
For the left-hand operand, the ruling differs. Left-shifting a negative is undefined, right-shifting it is implementation-defined.
Should this be interpreted to mean that left-shifting any negative number is UB?
Yes, the behavior is undefined when given any negative number. The behavior is only defined when both of the following are true:
- the number is non-negative
- E1 × 2E2 is representable in the result type
That's literally what "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," is saying:
if X and Y
then Z
else U