Vincent
Vincent

Reputation: 60491

In the expression bool << integer, is bool promoted to int, or to the same type as the integer?

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 ?

Upvotes: 3

Views: 731

Answers (1)

Barry
Barry

Reputation: 304122

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.

Upvotes: 3

Related Questions