ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
#define SWAP(a, b) do { int t = a; a = b; b = t; } while (0)
int main(void) {
    int x = 1, y = 2;
    if (x < y)
        SWAP(x, y);
    else
        printf("no swap");
    printf("%d %d", x, y);
}
  1. A. 1 2
  2. B. 2 1
  3. C. Compilation error
  4. D. no swap1 2

Correct answer: B. 2 1

The do { ... } while (0) wrapper makes the macro behave as a single statement syntactically, so it attaches cleanly to the if without braces, and the trailing semicolon is consumed correctly. x<y is true, so the swap runs: x becomes 2, y becomes 1.

More C Programming questions

Exams that ask this topic