Reputation: 427
I am trying to understand how the ternary operator works in C++.
I expect to see the same output for both print statements, yet the second print statement outputs 49.
Why is this?
#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
Upvotes: 2
Views: 97
Reputation: 2157
'1' got converted to an integer which represented the ASCII code for '1'. The ternary operator is supposed to have two values of the same type. You can not have 3 (an integer) and '1' (a char). That's why the conversion took place. If the implicit conversion could not have happened then a compiler error would have been generated.
Upvotes: 5