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.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
amitkumarusc
  • 862
  • 10
  • 24

2 Answers2

34

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.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
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.

marcinj
  • 48,511
  • 9
  • 79
  • 100
  • 2
    `static_cast('1')` is 49 on many systems, but it is not required. There are systems where it is not. – Pete Becker May 03 '15 at 21:33
  • 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. – edmz May 04 '15 at 12:25