Why we can't return anything in the ternary operator [duplicate]

  • A+
Category:Languages

This question already has an answer here:

Why this statement is showing error missing primary-expression before return for the following code.

(1==1) ? return 1 : return 0; 

 


The ternary operator deals in expressions, but return is a statement.

The syntax of the return statement is

return expr ;

The syntax of the ternary conditional operator is

expr1 ? expr2 : expr3

So you can plug in an invocation of the ternary operator as the expr in a return statement. But you cannot plug in a return statement as expr2 or expr3 of a ternary operator.

The ternary expression acts a lot like an if statement, but it is not an exact replacement for an if statement. If you want to write

if(1 == 1)      return 1; else return 0; 

you can write it as a true if statement, but you can't convert it to using ? : without rearranging it a little, as we've seen here.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: