mercredi 29 juin 2016

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.


Aucun commentaire:

Enregistrer un commentaire