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);
}
  1. A.

    2

  2. B.

    20

  3. C.

    22

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

  1. Evaluate v = 20: it stores 20 in v. This is the left operand of the comma expression, so its produced value is discarded after the side effect is complete.

  2. Evaluate v + 2: because v is now 20, the expression gives 20 + 2 = 22.

  3. The comma expression therefore has the value 22, and the outer assignment stores 22 in k.

  4. The call printf("%d", k) prints the integer stored in k.

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.

Explore the full course: Up Lt Grade Assistant Teacher 2025

Loading lesson…