What does '?' do in C++?

Thaier Alkhateeb picture Thaier Alkhateeb · Apr 27, 2009 · Viewed 209.3k times · Source
int qempty()
{
    return (f == r ? 1 : 0);
}

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

Answer

Daniel LeCheminant picture Daniel LeCheminant · Apr 27, 2009

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.