Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this ? operator in C++ do? [duplicate]

Consider this function

template<class T> inline bool cx(T &a, T b) {return a < b ? a = b, 1 : 0;}

Can anyone explain what exactly this is doing? It seems different from the typical condition ? true : false format.

like image 531
AJJ Avatar asked Jul 24 '15 16:07

AJJ


4 Answers

We could make it more clear like so:

return a < b ? (a = b, 1) : 0;

The parenthesized bit means "assign b to a, then use 1 as our value".

Comma-separated lists of values in C and C++ generally mean "evaluate all of these, but use the last one as the expression's value".

like image 83
Paul Roub Avatar answered Sep 28 '22 05:09

Paul Roub


This combination is a little tricky, because it combines a comma operator with the conditional expression. It parses as follows:

  • a < b is the condition,
  • a = b, 1 is the "when true" expression
  • 0 is the "when false" expression

The result of the comma operator is its last component, i.e. 1. The goal of employing the comma operator in the first place is to cause the side effect of assigning b to a.

like image 22
Sergey Kalinichenko Avatar answered Sep 28 '22 04:09

Sergey Kalinichenko


You can execute several expression using ,

In this case if a < b, then assign b to a and return 1. According C++ grammar:

conditional-expression:  
    logical-or-expression
|   logical-or-expression ? expression : assignment-expression

where

expression:  
    assignment-expression
|   expression , assignment-expression

assignment-expression:   
    conditional-expression
|   logical-or-expression assignment-operator initializer-clause
|   throw-expression
like image 30
Alex Avatar answered Sep 28 '22 06:09

Alex


The , operator just evaluates all the expressions, left to right, and evaluates to the value of the rightmost expression.

Your code is the same as...

if (a < b)
{
  a = b;
  return 1;
}
else
{
  return 0;
}
like image 34
QuestionC Avatar answered Sep 28 '22 05:09

QuestionC