Consider the following C program. # include <stdio.h> void mystery (int *ptra,…

2016

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 __________.

Attempted by 37 students.

Show answer & explanation

Correct answer: 2016

Key idea: function parameters are pointers passed by value. Swapping the pointer parameters inside the function only swaps the local copies, it does not change the caller's variables or which objects they point to.

  1. Initial values: a = 2016, b = 0, c = 4, d = 42.

  2. Call mystery(&a, &b): inside the function the local pointer variables are swapped, but the integers a and b are not modified and the caller's pointers are unaffected. After this call a remains 2016.

  3. Evaluate if (a < c): this checks whether 2016 < 4, which is false, so the call mystery(&c, &a) is skipped.

  4. Call mystery(&a, &d): again only local pointer copies are swapped; no integer values are changed. a remains 2016.

  5. Finally, printf prints the value of a, which is 2016.

Answer: 2016

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir