Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all parameters in ternary operator mandatory or can you do "(exp1 ? : value)"?

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?

like image 520
anna coobs Avatar asked Aug 30 '16 16:08

anna coobs


2 Answers

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

like image 189
Serge Avatar answered Sep 23 '22 10:09

Serge


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.

like image 36
haccks Avatar answered Sep 22 '22 10:09

haccks