8

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.

AJJ
  • 2,004
  • 4
  • 28
  • 42

6 Answers6

9

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".

Community
  • 1
  • 1
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
4

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

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;
}
QuestionC
  • 10,006
  • 4
  • 26
  • 44
3

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
Alex
  • 3,301
  • 4
  • 29
  • 43
1

Read it as:

if ( a < b )
{
    a = b;
    return ( 1 );
}
else
{
    return ( 0 );
}
unxnut
  • 8,509
  • 3
  • 27
  • 41
0

a < b ? a = b, 1 : 0 is parsed as (a < b) ? (a = b, 1) : 0, a normal conditional operator. When a < b is true, a = b, 1 is evaluated by assigning b to a and then "returning" 1. The net effect of cx(a,b) is thus to assign the larger value to a and to return 1 if a changed, 0 otherwise.

jwodder
  • 54,758
  • 12
  • 108
  • 124