2

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

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

4 Comments

More clearly: Every expression has a type at compile time: The type of (test ? 3 : '1') is the common type of the last two parts: int and char. And the common type of those is an int. And (on this machine) '1' is represented by the value 49 in hardware.
This effect can have other nasty surprises. See cppquiz.org/quiz/question/217
@alter igel Whoa, never new that about the ternary operator or cppquiz.org. Thanks for both!
@shargors I just found out about it recently. I think it could be very useful to help settle arguments about what code does between developers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.