Assuming an exam-style compiler that accepts void main() and recognizes…
2021
Assuming an exam-style compiler that accepts void main() and recognizes printf, what is the output of the following C program?
void main()
{
int k, v;
k = (v = 20, v + 2);
printf("%d", k);
}- A.
2
- B.
20
- C.
22
- D.
Error
Attempted by 747 students.
Show answer & explanation
Correct answer: C
Concept
In a comma expression E1, E2, C evaluates E1 first and then E2; the value of the whole expression is the value produced by E2. Parentheses can group that comma expression as the right-hand side of another assignment.
Evaluation order matters because every side effect from E1 is complete before E2 is evaluated. Hosted ISO C requires a standard form of main and appropriate declarations for library functions; exam snippets may instead rely on compiler extensions, so output analysis must state the assumed compilation convention.
Application
Evaluate
v = 20: it stores 20 inv. This is the left operand of the comma expression, so its produced value is discarded after the side effect is complete.Evaluate
v + 2: becausevis now 20, the expression gives 20 + 2 = 22.The comma expression therefore has the value 22, and the outer assignment stores 22 in
k.The call
printf("%d", k)prints the integer stored ink.
Cross-check
Track the state independently: after the left operand, v = 20; the right operand then produces 22; after the outer assignment, k = 22. Under strict hosted ISO C, the program should use int main(void) and include stdio.h, but the stem explicitly assumes an exam-style compiler that accepts and recognizes the shown code.
Result
The printed output is 22.