Search code examples
cassignment-operatorcomma-operator

How does this logic work: k+=(x=5,y=x+2,z=x+y) ;


How does this logic work: k+=(x=5,y=x+2,z=x+y);

How it will give result k == 22. When I initialize the value of k = 10

#include <stdio.h>
int main()
{
    int x,y,z,k=10;
    k+=(x=5,y=x+2,z=x+y);
    printf("value of k %d ",k); //why it will show value of k =22
    return 0;
}

Solution

  • In the right side of the assignment statement there is used the comma operator (sequentially two times from left to right). Its value is the value of the last operand. So this statement

    k+=(x=5,y=x+2,z=x+y);
    

    that can be for clarity rewritten like

    k+=( ( x = 5, y = x + 2 ), z = x + y );
    

    in fact is equivalent to the following set of statements

    x = 5;      // x is set to 5
    y = x + 2;  // y is set to 7
    z = x + y;  // z is set to 12
    k += z;     // k is set to 22
    

    From the C Standard (6.5.17 Comma operator)

    2 The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.