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

2019-01-04 21:12发布

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.

7条回答
做自己的国王
2楼-- · 2019-01-04 22:14

You need to know what the comma operator is doing here:

Your expression:

(i, ++i, 1)

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.

查看更多
登录 后发表回答