Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma and assignment operators in C

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 ?

like image 510
user963241 Avatar asked Dec 13 '12 15:12

user963241


People also ask

What do u mean by comma operator?

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.

What is comma and size of operator?

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) .

What does comma mean in binary?

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.


2 Answers

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.

like image 150
Graham Borland Avatar answered Sep 22 '22 07:09

Graham Borland


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.

like image 39
Fred Larson Avatar answered Sep 25 '22 07:09

Fred Larson