return statement in ternary operator c++

这一生的挚爱 提交于 2019-11-27 12:39:05

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

 return a

is a statement

Nandit Tiku

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;

What's the difference between the two?

One is correct syntax, the other is not.

?: 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;

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!