views:

183

answers:

4

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
+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
of just: return sum > 0; which works out as returning 1 or 0 anyway.
DrDipshit
@DrDipShit: very true, in this case that works just as well :)
WoLpH
+8  A: 

Because return is a statement, not an expression. You can't do int a = return 1; either.

jdv
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
-1, doesn't really answer the question. also SO is not designed to drive traffic to your website
Hasturkun