开发者

expected expression before return

开发者 https://www.devze.com 2022-12-14 11:38 出处:网络
the following c statement is not passing through compiler .error being \"expected expression before return\".

the following c statement is not passing through compiler .error being "expected expression before return".

           int max( int a,int b)
            {
                 a>b?return a:return b;
            }

and yeah ,i know i can write this fo开发者_开发技巧r finding max as

            return a>b?a: b;

which is quite okay and will run perfectly. but my question is what is exact problem with the first code.why cant we use return in ternary opoerator,although we can use function call quite easily over there?

THANKS in advance!!!


The C grammar says that the things after the '?' and the ':' must be expressions - return is not an expression, it is a statement.


The operands of ternary ?: are expressions. A return statement is a statement, not an expression.


?: is an operator not a control flow construct, so the whole thing with operands must be an expression, and return statements (or any statement) are not valid sub-expressions.

?: is not simply a shorthand for if-else (which is a control flow construct); it is semantically different.

if( a > b ) return a; else return b;

on the other hand is what you were trying to do, and entirely valid (if perhaps ill-advised stylistically).


The second and third parts of the ternary expression are expected to yield values, not be return statements as in your example.


Ternary operator needs expression,return is a statement.

More about conditional operator here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号