C++ 三元运算符c ++中的返回语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3918203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
return statement in ternary operator c++
提问by ameen
I wrote the absolute function using ternary operator as follows
我使用三元运算符编写了绝对函数,如下所示
int abs(int a) {
a >=0 ? return a : return -a;
}
I get the following error messages
我收到以下错误消息
../src/templates.cpp: In function ‘int abs(int)':
../src/templates.cpp:4: error: expected primary-expression before ‘return'
../src/templates.cpp:4: error: expected ‘:' before ‘return'
../src/templates.cpp:4: error: expected primary-expression before ‘return'
../src/templates.cpp:4: error: expected ‘;' before ‘return'
../src/templates.cpp:4: error: expected primary-expression before ‘:' token
../src/templates.cpp:4: error: expected ‘;' before ‘:' token
../src/templates.cpp:5: warning: no return statement in function returning non-void
If I write like this
如果我这样写
return a>=0 ? a : -a;
I don't get any error. What's the difference between the two?
我没有收到任何错误。两者有什么区别?
回答by The Archetypal Paul
The second and third arguments to the ternary operator are expressions, not statements.
三元运算符的第二个和第三个参数是表达式,而不是语句。
return a
is a statement
是一个声明
回答by 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;
回答by Gary Willoughby
What's the difference between the two?
两者有什么区别?
One is correct syntax, the other is not.
一种是正确的语法,另一种则不是。
回答by sth
?:
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.
?:
是一个运算符,它采用三个表达式并以某种方式计算它们以产生结果。return a
不是表达式(它是语句),因此您的第一种形式不起作用。这与您不能放入return
其他运算符的参数相同:return a + return b
也将不起作用。
If you want the returns in the separate branches, use if
instead:
如果您希望在单独的分支中返回,请if
改用:
if (a >=0)
return a;
else
return -a;
回答by Jonathan Leffler
Return is a statement and cannot be used where a value is expected.
Return 是一个语句,不能用于需要值的地方。
You must use expressions (which usually yield a value) in the three components of the ternary operator.
您必须在三元运算符的三个组件中使用表达式(通常会产生一个值)。