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.
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".
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" expression0
is the "when false" expressionThe 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
.
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With