Question
The output of the following C program is _____.
#include <stdio.h>
void f1(int a, int b) {
int c;
c = a; a = b; b = c;
}
void f2(int *a, int *b) {
int c;
c = *a; *a = *b; *b = c;
}
int main() {
int a = 4, b = 5, c = 6;
f1(a, b);
f2(&b, &c);
printf("%d", c - a - b);
return 0;
}
Official answer and solution
- Official answer
- -5
- From
- Official GATE 2015 answer key
Solution
Trace the C function calls, distinguishing between call-by-value and call-by-reference using pointers.
- In
main(), variables are initialized:a = 4,b = 5,c = 6. - Call
f1(a, b):
f1(int a, int b)receives arguments by value. The swaps withinf1affect only its local copies. On return, variables inmain()remain unchanged:a = 4,b = 5,c = 6. - Call
f2(&b, &c):
f2(int *a, int *b)receives the addresses ofbandcfrommain():
Thus, afterint c; // local variable in f2 c = *a; // c = 5 *a = *b; // *a (main's b) = 6 *b = c; // *b (main's c) = 5f2(&b, &c),bbecomes andcbecomes . - Evaluate the printf expression
c - a - b:
The output printed is -5.
Final answer
-5
Common trap
Assuming f1 modifies main's a and b, or miscalculating the arithmetic expression as .
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2015 Computer Science and Information Technology (CS) Session 1
- Question
- 21 of 65, printed as CS Q.11
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.