Predict the output of following C++ program.
One would expect the output will be same in both the print statements. However, the output will be,
Why the second statement printing 49? Read on the ternary expression.
Ternary Operator (C/C++):
A ternary operator has the following form,
exp1 ? exp2 : exp3
The expression
exp1 will be evaluated always. Execution of
exp2 and
exp3 depends on the outcome of
exp1. If the outcome of
exp1 is non zero
exp2 will be evaluated, otherwise
exp3 will be evaluated.
Side Effects:
Any side effects of
exp1 will be evaluated and updated immediately before executing
exp2 or
exp3. In other words, there is
sequence point after the evaluation of condition in the ternary expression. If either
exp2 or
exp3 have side effects, only one of them will be evaluated.
Return Type:
It is another interesting fact. The ternary operator has return type. The return type depends on exp
2, and
convertibility of exp
3 into exp
2 as per usual\overloaded conversion rules. If they are not convertible, the compiler throws an error. See the examples below,
The following program compiles without any error. The return type of ternary expression is expected to be
float (as that of exp
2) and exp
3 (i.e. literal
zero - int type) is implicitly convertible to
float.
The following program will not compile, because the compiler is unable to find return type of ternary expression or implicit conversion is unavailable between exp
2 (
char array) and exp
3 (
int).
The following program *may* compile, or but fails at runtime. The return type of ternary expression is bounded to type (
char *), yet the expression returns
int, hence the program fails. Literally, the program tries to print string at 0th address at runtime.