Why can't we use return keyword inside ternary operators in C, like this: sum > 0 ? return 1 : return 0;
+13
A:
return
is a statement. Statements cannot be used inside expressions in that manner.
Ignacio Vazquez-Abrams
2010-08-25 13:43:37
+11
A:
Because a ternary operation is an expression and you can't use statements in expresssions.
You can easily use a ternary operator in a return though.
return sum > 0 ? 1 : 0;
Or as DrDipShit pointed out:
return sum > 0;
WoLpH
2010-08-25 13:43:38
of just: return sum > 0; which works out as returning 1 or 0 anyway.
DrDipshit
2010-08-25 13:47:59
@DrDipShit: very true, in this case that works just as well :)
WoLpH
2010-08-25 15:03:25
+8
A:
Because return
is a statement, not an expression. You can't do int a = return 1;
either.
jdv
2010-08-25 13:43:52
A:
Hi,
See the syntax of a ternary operator is
expr1 ? expr2: expr3;
where expr1,expr2,expr3 are expressions;
The opertaor ?: works as follows expr1 is evaluated first if it is true expr2 is evluated otherwise expr3 is evluated.
hence in expressions the return statement can not be used in C-language.
thanks Kolla Sanjeeva ra
ksrao
2010-08-25 16:38:39
-1, doesn't really answer the question. also SO is not designed to drive traffic to your website
Hasturkun
2010-08-25 16:43:36