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):

  • p receives the address of i (p = &i). Any modification to *p directly modifies i in main().
  • m receives a copy of the value of j (m = 10). This is call-by-value, so changes to m have no effect on j in main().

Inside f:

  1. m = m + 5;   ⟹  m=10+5=15\implies m = 10 + 5 = 15.
  2. *p = *p + m;   ⟹  ∗p=5+15=20\implies *p = 5 + 15 = 20. Since p points to i, this sets i = 20.
  3. return;

Back in main():

  • i is now 20.
  • j remains unchanged at 10.
  • printf("%d", i + j); computes 20+10=3020 + 10 = 30 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.