comma operator

Again one of the confusing topic in c,comma operator.

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);
 
    return 0;
}
Guess the o/p and explanation.

Comments

  1. when we use comma operator, 1st operand is first evaluated and then second one. comma operator is a sequence point as well. when we have expression of the form y = ( 10,5 ); y gets the value 5(here 10 is discarded).
    but if y=10,5; then y gets 10 as its value. still if there are expressions involved all the expressions are evaluated and then discarded. so, for the above case the output is-
    x=11
    x=12
    y=12
    x=13

    had there been no brackets in the y expression, final value of y would have been 10.

    ReplyDelete
  2. perfect explanation.i would like to suggest one more thing.as you said if there are expression on left side they are evaluated and then discarded but there side-effect if any will remain in the program.
    In the above example
    y = (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++);
    value of x is incremented going from left to right...

    ReplyDelete

Post a Comment

Popular posts from this blog