ProgrammingHardWipro · Cognizant pattern

Assume 32-bit int. What is printed?

Assume 32-bit int. What is printed?
#define SWAP(a, b, type) do { type t = a; a = b; b = t; } while (0)
int main(void) {
    int x = 1, y = 2;
    SWAP(x, y, int);
    printf("%d %d", x, y);
}
  1. A. 1 2
  2. B. 2 1
  3. C. Compile-time error: macros cannot take a type as an argument
  4. D. Undefined behaviour

Correct answer: B. 2 1

Macro parameters are purely textual; passing int as the type argument substitutes it directly into type t = a;, becoming int t = a; — this works fine since the preprocessor doesn't distinguish between value and type arguments, it just pastes tokens. The swap correctly exchanges x and y: x becomes 2, y becomes 1.

More C Programming questions

Exams that ask this topic