Question

Consider the following C program.

#include <stdio.h>
void mystery(int *ptra, int *ptrb) {
    int *temp;
    temp = ptrb;
    ptrb = ptra;
    ptra = temp;
}
int main() {
    int a = 2016, b = 0, c = 4, d = 42;
    mystery(&a, &b);
    if (a < c)
        mystery(&c, &a);
    mystery(&a, &d);
    printf("%d\n", a);
}

The output of the program is _____.

Official answer and solution
Official answer
2016
From
Official GATE 2016 answer key

Solution

Trace pointer values and parameter passing in C to determine if variables in main are modified.

Inspect the function definition:

void mystery(int *ptra, int *ptrb) {
    int *temp;
    temp = ptrb;
    ptrb = ptra;
    ptra = temp;
}

In C, all function parameters are passed by value. Here, ptra and ptrb are local pointer variables initialized with the memory addresses passed by the caller.

The statements inside mystery only swap the local pointer variables ptra and ptrb. The integers pointed to (i.e. *ptra and *ptrb) are never dereferenced or modified. When mystery returns, its local variables are destroyed and the values in the caller's stack frame remain completely unchanged.

Trace execution in main():

  • int a = 2016, b = 0, c = 4, d = 42;
  • mystery(&a, &b); -> no change to a or b (a = 2016).
  • if (a < c) -> 2016 < 4 evaluates to false, so mystery(&c, &a) is skipped.
  • mystery(&a, &d); -> no change to a or d (a = 2016).
  • printf("%d\n", a); -> prints the unchanged value of a, which is 2016.
Final answer

2016

Common trap

Assuming mystery successfully swaps the integer values of a and b, which would require *temp = *ptrb; *ptrb = *ptra; *ptra = *temp;.

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 1
Question
25 of 65, printed as CS Q.15
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.