'Conditional operator is giving compilation error in c
(a>b) ? return a : return b;
This code is giving compilation error why
Solution 1:[1]
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;
Solution 2:[2]
It should be:
return (a>b) ? a : b;
Solution 3:[3]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vlad from Moscow |
| Solution 2 | 0___________ |
| Solution 3 |
