A swap that does not swap — Aptitude Question
A swap that does not swap: What does this C program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
What does this C program print?
#include <stdio.h>
void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
int main(void) {
int x = 3, y = 8;
swap(x, y);
printf("%d %d", x, y);
return 0;
}Options
- 3 8
- 3 3
- 8 3
- 8 8
Show the answer and the worked solution
Correct answer: A. 3 8
Worked solution
- C passes arguments by value, so a and b are private copies of x and y.
- The three lines do exchange those copies, leaving a = 8 and b = 3 inside the function.
- The copies vanish when swap returns, so x is still 3 and y is still 8, and the program prints 3 8.
Answer: 3 8.
The idea
C has only call by value, so a function can never change a caller's variable unless it is handed the address of that variable. Passing int * instead of int is the fix.
Shortcut. swap receives copies and returns nothing, so main's x and y cannot change: print them exactly as declared, 3 8.
Common trap. "8 3" trusts the function's name; the exchange happens only between the private copies a and b, which vanish on return.
All Programming Fundamentals questions · placement mock tests