3

Consider the following code:

// E1 << E2 with E1 bool, and E2 an integer
true << static_cast<char>(1);
true << static_cast<short int>(1);
true << static_cast<int>(1);
true << static_cast<unsigned int>(1);
true << static_cast<long long int>(1); 
true << static_cast<long long unsigned int>(1);

When doing the operation, is E1 promoted as the same type as E2, or is it promoted first to int and then to std::common_type<E1, E2>::type?

In other words, is:

true << static_cast<char>(9);

defined, or undefined behaviour ?

IngoAlbers
  • 5,722
  • 6
  • 31
  • 45
Vincent
  • 57,703
  • 61
  • 205
  • 388
  • C doesn't really have a "bool" type. C99 adds `_Bool`, but it's effectively an `int` with the acceptable values of `1` or `0`. This question is only about C++. – PC Luddite Sep 26 '15 at 19:02

1 Answers1

3

From [expr.shift]:

The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand.

From [conv.prom]:

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

Integral promotion on bool produces int. So the result type of true << (any integral type) is int. true << static_cast<char>(9) after integral promotion is the same as 1 << 9, which is well-defined as 512.

Barry
  • 286,269
  • 29
  • 621
  • 977