In C, why expression(Statement) containing comma(,) operator work differently
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.
operator comma is to execute many statement and return only result of last statement.
So for c=i=j,++i;
: c=i=j
is executed, then ++i
and after that result of ++i
is returned (but not used).
And for c=(i=j,++i);
, according to operator precedence, i=j
is executed, and just after ++i
is executed, and then affectation to c
of result of (i=j, ++i)
, which is the result of last statement, i.e. ++i
So, the behavior of comma is not really same as semicolon. You can use it as a substitute like in c=i=j,++i;
.
Personally, I do not encourage to use this operator, which generates less readable and less maintainable code
What is the actual work of comma(,) as an operator?
The comma operator is mainly a superfluous feature. See this for a description of how it works.
++ has more precedence than , and =, why evaluation is done for the expression on left of comma? What will be the order if an expression contains operators with different priority, will it depend on comma(,)?
The left operand is evaluated for side effects. The result of the comma operator is the result of the evaluated right operand. Note that the comma operator has the lowest precedence of all operators in C.
Is it behaving like a substitute of semicolon(;)?
Kind of, yeah. Both a semi-colon and the comma operator includes a sequence point. The difference is that the comma operator isn't the end of a statement, so it can be squeezed in with other operators on the same line, and it also returns a result.
There is really no reason why you ever would want to do this though. The main use of the comma operator is to obfuscate code, it should be avoided. The only reason why you need to learn how it works, is because you might encounter crap code containing it.
For example, your nonsense code should be rewritten into something more readable and safe:
int main(){
int i=0;
int j=11;
int c;
i=j;
c=j;
i++;
printf("c=%d i=%d\n",c,i);
i=j;
i++;
c=i;
printf("c=%d i=%d\n",c,i);
return 0;
}