Search code examples
ctypesincrement

C incrementation and variable declaration


I have this question for a practice test in C that I don't understand. Show the output of the following program

x = y = 3;
y = x++, x++;
printf("x = %d, y = %d\n", x, y);

Answer: 1 x = 5, y = 3

I dont understand what

x++, x++ 

Does x++ mean to implement the value of x into y then add one to it, but why is there a comma ? Would it just first add the value of x in y, and do x=x+1 twice?

I tried putting it in a compiler, found some struggles.


Solution

  • In this statement:

    y = x++, x++;
    

    It contains both the assignment operator and the comma operator as well as the postfix increment operator. Of these the postfix increment operator has the highest precedence followed by the assignment operator, then the comma operator. So the expression parses as this:

    (y = (x++)), (x++);
    

    The comma operator first evaluates its left operand for any side effects and discards the value of that operand. There is a sequence point here before it then evaluates its right operand, which means evaluating left side and all side effect are guaranteed to occur before those on the right side.

    So let's first look at the left operand of the comma operator:

    y = (x++)
    

    The subexpression x++ evaluates to the current value of x and increments x as a side effect. At this point x has the value 3, so y gets assigned the value 3 and x is incremented to 4.

    Now for the right side:

    x++
    

    Since x currently has the value 4, it is incremented to now contain the value 5.

    So at the end x is 5 and y is 3.