231 isn't representable in a int32_t
, which goes from -231 to (231-1). This is undefined behavior in C11 and C++11, and implementation-defined in C++14.
C11 §6.5.7/p4 (quoting N1570):
The result of E1 << E2
is E1
left-shifted E2
bit positions;
vacated bits are filled with zeros. [...] If E1
has a signed type
and nonnegative value, and E1 × 2
E2
is representable in
the result type, then that is the resulting value; otherwise, the
behavior is undefined.
The C++11 rule in N3337 §5.8 [expr.shift]/p2 is pretty much identical. Since 231 isn't representable, the behavior is undefined.
C++14 §5.8 [expr.shift]/p2 (quoting N3936; see also CWG issue 1457):
The value of E1 << E2
is E1
left-shifted E2
bit positions;
vacated bits are zero-filled. [...] 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.
As 231 is representable in an unsigned 32-bit int, the behavior is defined and the result is 231 converted to int32_t
; this conversion is implementation-defined per §4.7 [conv.integral]/p3. In a typical system using two's complement you'd get -231.