ame*_*een 31 c++ return ternary
我使用三元运算符编写了绝对函数,如下所示
int abs(int a) {
a >=0 ? return a : return -a;
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息
../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
Run Code Online (Sandbox Code Playgroud)
如果我这样写
return a>=0 ? a : -a;
Run Code Online (Sandbox Code Playgroud)
我没有得到任何错误.这两者有什么区别?
小智 33
你的语法不正确.它应该是
if (a >=0)
return a;
else
return -a;
Run Code Online (Sandbox Code Playgroud)
或者你想要的方式:
return a >=0 ? a : -a;
Run Code Online (Sandbox Code Playgroud)
?:是一个运算符,它接受三个表达式并以某种方式计算它们以产生结果.return a不是表达式(它是一个声明),所以你的第一个表单不起作用.它与你不能放入return其他运算符的参数一样:return a + return b也不会起作用.
如果您想要在单独的分支中返回,请if改为使用:
if (a >=0)
return a;
else
return -a;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32752 次 |
| 最近记录: |