What will the following C code print? int value, x, y; value = (x = 10, y = 5,…
2026
What will the following C code print?
int value, x, y;
value = (x = 10, y = 5, x + y);
printf("Value = %d", value);Answer: C. Value = 15 — Concept. Used as an operator, the comma in C is a sequencing operator: in an expression a, b the left operand is evaluated first and its value is discarded,…
- A.
Value = 10
- B.
Value = 5
- C.
Value = 15
- D.
Error
Attempted by 224 students.
Show answer & explanation
Correct answer: C
Concept. Used as an operator, the comma in C is a sequencing operator: in an expression a, b the left operand is evaluated first and its value is discarded, and the value and type of the whole expression are those of the rightmost operand. Each comma is a sequence point, so every side effect of one operand is complete before the next operand begins.
Application.
The parentheses in
(x = 10, y = 5, x + y)enclose one comma expression with three operands, so the operands are evaluated strictly left to right.The first operand
x = 10is evaluated: it stores 10 inx. The value it produces is discarded at the comma.The second operand
y = 5is evaluated: it stores 5 iny. Its value is discarded at the next comma.The third and rightmost operand
x + yis evaluated with the stored values: 10 + 5 = 15. Because it is the rightmost operand, 15 is the value of the whole parenthesised expression.That value is assigned to
value, sovalueholds 15 andprintf("Value = %d", value)writesValue = 15.
Cross-check. The snippet is well-formed C: the commas in the declaration int value, x, y; are declarator separators, the commas inside the parentheses form a comma expression, and the %d conversion specifier is paired with an int argument, so nothing here is a constraint violation. Treating only the first assignment as the expression’s value would give 10, and treating only the second as its value would give 5; both readings ignore that a comma expression takes the value of its last operand, which is why the sum 15 is what reaches value.