What does the question mark character ('?') mean in C++?

What does the question mark character ('?') mean in C++?

眼泪淡了忧伤 发布于 2021-11-27 字数 159 浏览 810 回复 8 原文
int qempty()
{
    return (f == r ? 1 : 0);
}

In the above snippet, what does "?" mean? What can we replace it with?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

百善笑为先 2022-06-07 8 楼

It read as:

If f == r then return 1 else return 0
甜心小果奶 2022-06-07 7 楼

The question mark is the conditional operator. The code means that if f==r then 1 is returned, otherwise, return 0. The code could be rewritten as

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

which is probably not the cleanest way to do it, but hopefully helps your understanding.

夏天碎花小短裙 2022-06-07 6 楼

It's the conditional operator.

a ? b : c

It's a shortcut for IF/THEN/ELSE.

means: if a is true, return b, else return c. In this case, if f==r, return 1, else return 0.

海的爱人是光 2022-06-07 5 楼

It is called the conditional operator.

You can replace it with:

int qempty(){ 
    if (f == r) return 1;
    else return 0;
}
从来不烧饼 2022-06-07 4 楼

You can just rewrite it as:

int qempty(){ return(f==r);}

Which does the same thing as said in the other answers.

孤星 2022-06-07 3 楼

Just a note, if you ever see this:

a = x ? : y;

It's a GNU extension to the standard (see https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html).

It is the same as

a = x ? x : y;
百善笑为先 2022-06-07 2 楼

This is a ternary operator, it's basically an inline if statement

x ? y : z

works like

if(x) y else z

except, instead of statements you have expressions; so you can use it in the middle of a more complex statement.

It's useful for writing succinct code, but can be overused to create hard to maintain code.

手心的温暖 2022-06-07 1 楼

This is commonly referred to as the conditional operator, and when used like this:

condition ? result_if_true : result_if_false

... if the condition evaluates to true, the expression evaluates to result_if_true, otherwise it evaluates to result_if_false.

It is syntactic sugar, and in this case, it can be replaced with

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

Note: Some people refer to ?: it as "the ternary operator", because it is the only ternary operator (i.e. operator that takes three arguments) in the language they are using.