相关疑难解决方法(0)

三元运算符c ++中的return语句

我使用三元运算符编写了绝对函数,如下所示

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)

我没有得到任何错误.这两者有什么区别?

c++ return ternary

31
推荐指数
5
解决办法
3万
查看次数

标签 统计

c++ ×1

return ×1

ternary ×1