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.
The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.
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.
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.
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 .
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With