问号字符('?')在C++中是什么意思?

2022-03-01 00:00:00 operators conditional-operator c++
int qempty()
{
    return (f == r ? 1 : 0);
}
在上面的代码段中,&q;?&q;是什么意思?我们可以用什么替换它?


解决方案

通常称为conditional operator,这样使用时:

condition ? result_if_true : result_if_false

..。如果condition求值为true,则表达式求值为result_if_true,否则求值为result_if_false

为syntactic sugar,此时可替换为

int qempty()
{ 
  if(f == r)
  {
      return 1;
  } 
  else 
  {
      return 0;
  }
}

注意:有人将?:称为"三元运算符",因为它是他们使用的语言中唯一的三元运算符(即接受三个参数的运算符)。

相关文章