Search code examples
coperatorsoperator-keywordcomma-operator

In C, why expression(Statement) containing comma(,) operator work differently


I have a simple C code and big confusion about expressions containing comma(,) operator(s).

int main(){
    int i=0,j=11,c;
    c=i=j,++i;
    printf("c=%d i=%d\n",c,i);
    c=(i=j,++i);
    printf("c=%d i=%d\n",c,i);
    return 0;
}

The above code prints:

c=11 i=12
c=12 i=12

My questions are:

  1. What is the actual work of comma(,) as an operator?
  2. ++ has more precedence than , and =, why evaluation is done for the expression on left of comma?
  3. What will be the order if an expression contains operators with different priority, will it depend on comma(,)?
  4. Is it behaving like a substitute of semicolon(;)?

Solution

  • The assignment operator has a higher priority then the comma operator. Thus expression

    c = i = j, ++i;
    

    is equivalent to

    ( c = i = j ), ++i;
    

    According to 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.114)

    In the expression above the result of the comma operator is discarded but it has a side effect of increasing i.

    In this expression

    c = ( i = j, ++i );
    

    due to using parentheses you changed the order of the evaluation of the above expression. Now it is equivalent to

    c = ( ( i = j ), ++i );
    

    and variable c gets the value of expression ++i according to the quote from the C Standard listed above.