After reading this answer about undefined behavior and sequence points, I wrote a small program:
#include <stdio.h>
int main(void) {
int i = 5;
i = (i, ++i, 1) + 1;
printf("%d\n", i);
return 0;
}
The output is 2
. Oh God, I didn't see the decrement coming! What is happening here?
Also, while compiling the above code, I got a warning saying:
px.c:5:8: warning: left-hand operand of comma expression has no effect
[-Wunused-value] i = (i, ++i, 1) + 1; ^
Why? But probably it will be automatically answered by the answer of my first question.
You need to know what the comma operator is doing here:
Your expression:
The first expression,
i
, is evaluated, the second expression,++i
, is evaluated, and the third expression,1
, is returned for the whole expression.So the result is:
i = 1 + 1
.For your bonus question, as you see, the first expression
i
has no effect at all, so the compiler complains.