Tha*_*eeb 65 c++ operators ternary-operator
int qempty()
{
return (f == r ? 1 : 0);
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码片段中," ? "是什么意思?我们可以用什么替代它?
Dan*_*ant 115
这通常被称为条件运算符,当使用时如下:
condition ? result_if_true : result_if_false
Run Code Online (Sandbox Code Playgroud)
...如果condition求值为true,则表达式求值为result_if_true,否则求值为result_if_false.
它是语法糖,在这种情况下,它可以替换为
int qempty()
{
if(f == r)
{
return 1;
}
else
{
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
注意:有些人将?:其称为" 三元运算符 ",因为它是他们使用的语言中唯一的三元运算符(即运算符采用三个参数).
小智 14
这是一个三元运算符,它基本上是一个内联if语句
x ? y : z
Run Code Online (Sandbox Code Playgroud)
像
if(x) y else z
Run Code Online (Sandbox Code Playgroud)
除了你有表达的陈述,而不是 所以你可以在更复杂的语句中使用它.
它对于编写简洁的代码很有用,但可以过度使用来创建难以维护的代码.
它被称为条件运算符.
您可以将其替换为:
int qempty(){
if (f == r) return 1;
else return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
请注意,如果您看到以下内容:
a = x ? : y;
Run Code Online (Sandbox Code Playgroud)
它是标准的GNU扩展(请参阅https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html#Conditionals)。
与...相同
a = x ? x : y;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
182947 次 |
| 最近记录: |