Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of ternary expression

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.

like image 260
amitasviper Avatar asked May 03 '15 20:05

amitasviper


People also ask

What are the types of ternary operator?

The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.

What are the 3 operands in ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

What is ternary expression in C?

The ternary operator is used to execute code based on the result of a binary condition. It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a function.

Why is it called a ternary expression?

The name ternary refers to the fact that the operator takes three operands. The condition is a boolean expression that evaluates to either true or false .


1 Answers

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

like image 83
Kerrek SB Avatar answered Sep 22 '22 18:09

Kerrek SB