Type of ternary expression
Asked Answered
M

2

31

Can anyone explain the output of the following program:

#include <iostream>
using namespace std;

int main()
{
   int test = 0;
   cout << "First  character " << '1' << endl;
   cout << "Second character " << (test ? 3 : '1') << endl;

   return 0;
}

Output:
First character 1
Second character 49

But both the printf statements should print the same line.

Mornay answered 3/5, 2015 at 20:11 Comment(1)
It is a good question, but unrelated to side-effects.Torgerson
W
33

The type of the expression '1' is char.

The type of the expression (test ? 3 : '1') is at least int (or an unsigned version thereof; portably it is std::common_type_t<int, char>).

Therefore the two invocations of the << operator select different overloads: The former prints the character as is, the latter formats the integer as its decimal string representation. (The integral value of the character '1' is defined by your base character set.)

Withdrawn answered 3/5, 2015 at 20:14 Comment(0)
N
5

cout will display value of (test ? 3 : '1') expression after deducing appropriate <<operator. In this case it is int, you can check it using nice trick that Scott Meyers propagated in his newest book:

template < typename T > class TD; // Type Displayer
int main()
{
  int test = 0;
  TD<decltype((test ? 3 : '1'))> xType; 

  return 0;
}

this generates error, which will also give you information of type of your expression:

main.cpp:6:34: error: aggregate 'TD<int> xType' has incomplete type and cannot be defined TD xType;

which is int. And static_cast<int>('1') is 49.

Neoclassicism answered 3/5, 2015 at 20:24 Comment(2)
static_cast<int>('1') is 49 on many systems, but it is not required. There are systems where it is not.Varipapa
IIIRC, string literals / chars are not required to be in ASCII format unless you specify the format (e.g. u8). There should be a question about that too.Araucaria

© 2022 - 2024 — McMap. All rights reserved.