c - What does i = (i, ++i, 1) + 1; do? -


after reading this answer undefined behavior , sequence points, wrote small program:

#include <stdio.h>  int main(void) {   int = 5;   = (i, ++i, 1) + 1;   printf("%d\n", i);   return 0; } 

the output 2. oh god, didn't see decrement coming! happening here?

also, while compiling above code, got warning saying:

px.c:5:8: warning: left-hand operand of comma expression has no effect

  [-wunused-value]   = (i, ++i, 1) + 1;                         ^ 

why? automatically answered answer of first question.

in expression (i, ++i, 1), comma used comma operator

the comma operator (represented token ,) binary operator evaluates first operand , discards result, , evaluates second operand , returns value (and type).

because discards first operand, only useful first operand has desirable side effects. if side effect first operand not takes place, compiler may generate warning expression no effect.

so, in above expression, leftmost i evaluated , value discarded. ++i evaluated , increment i 1 , again value of expression ++i discarded, but side effect i permanent. 1 evaluated , value of expression 1.

it equivalent

i;          // evaluate , discard value. has no effect. ++i;        // evaluate , increment 1 , discard value of expression ++i = 1 + 1;   

note the above expression valid , not invoke undefined behavior because there sequence point between evaluation of left , right operands of comma operator.


Comments