Search code examples
c++operatorsoperator-precedence

Does operator ',' always returns the second argument?


In GCC

#include <iostream>
int main() {
  if(1 == 2, true) {
    std::cout << "right" << std::endl;
  } else std::cout << "left" << std::endl;
  return 0;
}

it output 'right', is it always so?


Can compiler just optimize out the left operand, as it didn't used?

warning: left operand of comma operator has no effect [-Wunused-value]
   if(1 == 2, true) {
      ~~^~~~

I have some code like this:

if(doSomethingHereWhichAlwaysReturnsTrue,
     doSomeOtherHereAndDependOnTheResultExecuteBodyOrNot) {
  ..body.. - execute if 'doSomeOther' returns true
}

Through this code is debug only, i wonder i can use such a construction in the release. I guess no.


To not ask twice, i'm also use sometimes assignment chaining like:

int i, j, k, l;
i = j = k = l = 0;

is it safe?

I heard once that the execution order is undefined and so this is an undefined behaviour. And as UB it can be clearly optimized out by the compiler, but using '-O3 -Wall -pedantic' i see no warnings with it, and the expected result, so i guess there no problems here.


Solution

  • The C++ Standard 5.18 says

    A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discardedvalue expression (Clause 5).86 Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, and is a bit-field if its right operand is a glvalue and a bit-field. If the value of the right operand is a temporary (12.2), the result is that temporary.

    So yes, according to the standard, returning the value of the second operand is the expected behavior.

    However, you can overload comma operator, and in this case, it can return whatever you would like to.