I would like to know if in the ternary operator in language C all parameters are mandatory? e.g.:
(exp1 ? : value2);
or you need to write:
(expr1 ? value1: value2);
I asked that because if you write: (exp1 ? : value2);
What return if the expr1
is TRUE?
It not a standard, but GCC extension (may be some other compilers do the same):
5.7 Conditionals with Omitted Operands
The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.
Therefore, the expression
x ? : y
has the value of x if that is nonzero; otherwise, the value of y.
This example is perfectly equivalent to
x ? x : y
Edit:
As @MadPhysicist pointed, that shortened form would evaluate the x
once, while the traditional form would re-evaluate the x
second time when x
is non-zero
The statement
(exp1 ? : value2);
is equivalent to
(exp1 ? exp1 : value2);
It is a GCC extension. The only difference in both of them is that exp1
will be evaluated only once in the former statement.
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