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);
}- A. 1 2
- B. 2 1
- C. Compile-time error: macros cannot take a type as an argument
- 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
- Assume 32-bit int. What is printed? c int x = 5, y = 3; int result = x++ - ++y; printf("%d %d %d", x, y, result);
- What is printed? c int main(void) { int a = 1, b = 2, c = 3, d = 4; int result = (a < b) ? ((c < d) ? 1 : 2) : ((c < d) ? 3 : 4)…
- What is printed? c int main(void) { int scores[5] = {85, 92, 78, 95, 88}; int max = scores[0]; for (int i = 1; i < 5; i++) { if (scores[i]…
- Assume a 64-bit LP64 ABI. What is printed? c struct Pair { int first; int second; }; struct Pair makePair(int a, int b) { return (struct…
- What is printed? c int main(void) { int n = 6; int result = 1; for (int i = n; i > 1; i--) result = i; printf("%d", result); }
- What is printed? c int main(void) { int x = 5, y = 5; if (x = y) printf("true:%d", x); else printf("false:%d", x); }