Ternary operators and Return in C

前端 未结 7 1172
一向
一向 2020-12-02 23:23

Why can\'t we use return keyword inside ternary operators in C, like this:

sum > 0 ? return 1 : return 0;
相关标签:
7条回答
  • 2020-12-02 23:55

    return is a statement. Statements cannot be used inside expressions in that manner.

    0 讨论(0)
  • 2020-12-02 23:56

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

    0 讨论(0)
  • 2020-12-02 23:59

    The return statement is used for returning from a function, you can't use inside ternary operator.

     (1==1)? return 1 : return 0; /* can't use return inside ternary operator */
    

    you can make it like

    return (1==1) ? 1 : 0;
    

    The syntax of a ternary operator follows as

    expr1 ? expr2 : expr3;
    

    where expr1, expr2, expr3 are expressions and return is a statement, not an expression.

    0 讨论(0)
  • 2020-12-03 00:03

    The ternary operator deals in expressions, but return is a statement.

    The syntax of the return statement is

    return expr ;

    The syntax of the ternary conditional operator is

    expr1 ? expr2 : expr3

    So you can plug in an invocation of the ternary operator as the expr in a return statement. But you cannot plug in a return statement as expr2 or expr3 of a ternary operator.

    The ternary expression acts a lot like an if statement, but it is not an exact replacement for an if statement. If you want to write

    if(sum > 0)
         return 1;
    else return 0;
    

    you can write it as a true if statement, but you can't convert it to using ? : without rearranging it a little, as we've seen here.

    0 讨论(0)
  • 2020-12-03 00:08

    See the syntax of a ternary operator is

    expr1 ? expr2: expr3;
    

    where expr1, expr2, expr3 are expressions;

    The operator ?: works as follows expr1 is evaluated first if it is true expr2 is evaluated otherwise expr3 is evaluated.

    hence in expressions the return statement can not be used in C-language.

    0 讨论(0)
  • 2020-12-03 00:17

    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;
    
    0 讨论(0)
提交回复
热议问题