comma operator

plz xplain the output of the following

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main()
{
int x = 10, y;
y = (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++);
printf("y = %d\n", y);
printf("x = %d\n", x);
getchar();
return 0;
}
The comma operator returns the result of the right operand. So if the left operand doesn't do anything as a statement by itself, you can ignore it.

Just don't get confused by the comma operator and using commas to separate parameters passed to a function.
According to the C++ standard regarding the comma operator

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.


So in the statement
y = (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++);

the sequence of actions is the following

1) x++
2) the side effect is sequenced x == 11
3) printf("x = %d\n", x) - outputs x == 11
4) ++x x == 12
5) printf("x = %d\n", x) outputs x == 12
6) x++ The value of the expression is 12
7) y = 12
8) the side effect is sequenced after the full expression; x == 13

After that you print values of y and x that is 12 and 13.

printf("y = %d\n", y);
printf("x = %d\n", x);
Last edited on
Topic archived. No new replies allowed.