ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
int swap_trick(int a, int b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("%d %d ", a, b);
return a + b;
}
int main(void) {
printf("%d", swap_trick(5, 9));
}- A. 9 5 14
- B. 5 9 14
- C. 9 5 4
- D. 0 0 0
Correct answer: A. 9 5 14
The classic XOR-swap: after a=a^b, b=a^b (which is (a^b)^b = original a), a=a^b (which is (a^b)^(original a) = original b). So a and b end up swapped: a=9, b=5, sum still 14.
More C Programming questions
- What is printed? c #define SETBIT(x, n) ((x) | (1 << (n))) #define CLEARBIT(x, n) ((x) & ~(1 << (n))) #define TOGGLEBIT(x, n) ((x) ^ (1 <<…
- What is printed? c #define SQUARE(x) x x int main(void) { int a = 5; printf("%d", SQUARE(a + 1)); }
- What is printed? c #define TWICE(x) x + x printf("%d", 2 TWICE(3));
- What is printed? c #define LOG(msg) printf("[LOG] %sn", msg) #ifdef DEBUG #define TRACE(msg) LOG(msg) #else #define TRACE(msg) #endif int…
- What is printed? c #define CONCAT(a, b) a##b int xy = 42; printf("%d", CONCAT(x, y));
- What is printed? c #if defined(STDC) && STDCVERSION >= 199901L int x = 10; #else int x = 20; #endif printf("%d", x);