Given below are three implementations of the swap() function in C++ : Which of…

2018

Given below are three implementations of the swap() function in C++ :

image.png

Which of these would actually swap the contents of the two integer variables p and q?

  1. A.

    (a) only

  2. B.

    (b) only

  3. C.

    (c) only

  4. D.

    (b) and (c) only

Attempted by 134 students.

Show answer & explanation

Correct answer: B

Answer: Only the implementation that takes parameters by reference (void swap(int &a, int &b)) swaps the original integers.

  • Pass-by-value version (void swap(int a, int b)): does not swap the originals because the function works on copies of p and q. Modifying a and b inside the function does not affect the variables in main.

  • Pass-by-reference version (void swap(int &a, int &b)): works because references alias the caller's variables. Assigning to a and b inside the function updates p and q in main.

  • Pointer version as written (void swap(int *a, int *b) with int *temp; temp = a; a = b; b = temp;): does not swap the integer values. That code swaps only the local copies of the pointer variables; it does not change the memory contents pointed to by the pointers.

  • Correct pointer-based swap: to swap the integers through pointers, dereference them:

    int temp; temp = *a; *a = *b; *b = temp;

Conclusion: Only the reference-based implementation actually swaps the contents of p and q as shown. The pass-by-value version operates on copies, and the pointer version shown swaps local pointer copies rather than the integer values.

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

Explore the full course: Nta Ugc Net Paper 2

Loading lesson…