Search code examples
ccomma-operator

Behavior of comma operator in C


If I write code using comma operator like this:

int i;
i = 5, i++, i++;

does it invoke undefined behavior?


Solution

  • No. It will not invoke undefined behavior as there is a sequence point between evaluation of left and right operands of comma operators.

    = has higher precedence than that of , operator and therefore 5 will bind to = as

    (i = 5), i++, i++;
    

    Since operands of comma operator guaranteed to evaluates from left to right, i = 5 will be evaluated first and i will be assigned 5, then the second expression i++ will be evaluated and i will be 6 and finally the third expression will increment i to 7.

    The above statement is equivalent to

    i = 5;
    i++;
    i++;