return statement in ternary operator c++

前端 未结 5 1446
不知归路
不知归路 2020-12-02 23:01

I wrote the absolute function using ternary operator as follows

int abs(int a) {
 a >=0 ? return a : return -a;
}

I get the following er

相关标签:
5条回答
  • 2020-12-02 23:20

    ?: is an operator that takes three expressions and evaluates them in some way to produce a result. return a is not an expression (it's a statement), so your first form doesn't work. It's the same as you can't put return in the arguments of other operators: return a + return b will also not work.

    If you want the returns in the separate branches, use if instead:

    if (a >=0)
       return a;
    else
       return -a;
    
    0 讨论(0)
  • 2020-12-02 23:23

    The second and third arguments to the ternary operator are expressions, not statements.

     return a
    

    is a statement

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

    Your syntax is incorrect. It should be

    if (a >=0)
        return a;
    else
        return -a;
    

    or the way you wanted it:

    return a >=0 ? a : -a;
    
    0 讨论(0)
  • 2020-12-02 23:34

    Return is a statement and cannot be used where a value is expected.

    You must use expressions (which usually yield a value) in the three components of the ternary operator.

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

    What's the difference between the two?

    One is correct syntax, the other is not.

    0 讨论(0)
提交回复
热议问题