Question
The value printed by the following program is ________.
void f(int* p, int m){
m = m + 5;
*p = *p + m;
return;
}
void main(){
int i=5, j=10;
f(&i, j);
printf("%d", i+j);
}Official answer and solution
- Official answer
- 30
- From
- Official GATE 2016 answer key
Solution
Trace the pointer dereferencing and pass-by-value argument modifications during the function call.
In main():
int i = 5, j = 10;
f(&i, j);
Examine the function signature and execution of f(int* p, int m):
preceives the address ofi(p = &i). Any modification to*pdirectly modifiesiinmain().mreceives a copy of the value ofj(m = 10). This is call-by-value, so changes tomhave no effect onjinmain().
Inside f:
m = m + 5;.*p = *p + m;. Sinceppoints toi, this setsi = 20.return;
Back in main():
iis now 20.jremains unchanged at 10.printf("%d", i + j);computes and prints 30.
Final answer
30
Common trap
Assuming j was also modified by the function call (mistaking pass-by-value for pass-by-reference).
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2016 Computer Science and Information Technology (CS) Session 2
- Question
- 22 of 65, printed as CS Q.12
- 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.