Why does left shift operation invoke Undefined Behaviour when the left side operand has negative value?

The paragraph you copied is talking about unsigned types. The behavior is undefined in C++. From the last C++0x draft:

The value of E1 << E2 is E1
left-shifted E2 bit positions; vacated
bits are zero-filled. If E1 has an
unsigned type, the value of the result
is E1 × 2E2, reduced modulo one more
than the maximum value representable
in the result type. Otherwise, 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
.

EDIT: got a look at C++98 paper. It just doesn’t mention signed types at all. So it’s still undefined behavior.

Right-shift negative is implementation defined, right. Why? In my opinion: It’s easy to implementation-define because there is no truncation from the left issues. When you shift left you must say not only what’s shifted from the right but also what happens with the rest of the bits e.g. with two’s complement representation, which is another story.

Leave a Comment