Home > Blockchain >  Conditional operator is giving compilation error in c
Conditional operator is giving compilation error in c

Time:05-20

(a>b) ? return a : return b;

This code is giving compilation error why

CodePudding user response:

The conditional operator is defined the following way

logical-OR-expression ? expression : conditional-expression

That is it consists from three expressions.

However instead of the second and the third expressions

(a>b) ? return a : return b;

you placed the statement return. So the compiler issues an error.

Instead you need to write a return statement with an expression containing the conditional operator like

return (a>b) ? a : b;

CodePudding user response:

It should be:

return (a>b) ? a : b;

CodePudding user response:

return a doesn't evaluate to a value, which is an obvious requirement of the conditional operator's operands. How can the whole evaluate to a value if its operands don't evaluate to a value?

In more technical terms, operands must be expressions. return a; would be a valid statement, but return a isn't a valid expression because it doesn't evaluate to a value. This isn't specific to the conditional operator (?:). For example, x return y and x && return y are just as invalid (in C).

You could use

return a>b ? a : b;
  • Related