I have the following:
int a = 1, b = 2, c = 3, d = 4;
a = b, c = d;
printf("%d, %d, %d, %d", a, b, c, d);
The output is:
2, 2, 4, 4
How does the comma operator work with assignment operators? From what I have known it would evaluate and return the second expression if we have,
(exp1, exp2)
So, why would it evaluate a = b
?
The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.
The comma operator has no special meaning to sizeof . sizeof(b, a) examines the complete expression (b, a) , works out the resultant type, and computes the size of that type without actually evaluating (b , a) .
The comma operator is a binary operator, that evaluates its first operand, and then discards the result, then evaluates the second operand and returns the value.
The first operand is evaluated and the result discarded. The second operand is then evaluated, and the result returned as the overall result of the expression.
The standard says:
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.
The comma operator is lower precedence than assignment. All expressions in a comma operator are evaluated, but only the last is used as the resulting value. So both assignments are performed. The result of the comma operator in your case would be the result of c = d
. This result is not used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With