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);
}- A. 1 2
- B. 2 1
- C. Compilation error
- 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
- What is printed? c #define A 1 #define B (A + 1) #undef A #define A 10 int main(void) { printf("%d", B); }
- What is printed? c #define FOO 10 #define BAR FOO + 5 int main(void) { int x = BAR 2; printf("%d", x); }
- What is printed? c #define LOG(msg) printf("[LOG] %s line %dn", msg, LINE) int main(void) { LOG("start"); LOG("end"); }
- What is printed? c #define TRUE 1 #define FALSE 0 #define BOOL int BOOL flag = TRUE; int main(void) { if (flag == TRUE) printf("yes")…
- What is printed? c #define CLAMP(x, lo, hi) ((x) < (lo) ? (lo) : (x) > (hi) ? (hi) : (x)) int main(void) { printf("%d %d %d", CLAMP(5, 1…
- What is printed? Assume int is 32-bit, two's complement. c int x = INTMAX; int y = x + 1; printf("%d", y);