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

Which of these would actually swap the contents of the two integer variables p and q?
Answer: B. (b) only — ConceptA function parameter is initialized from its argument. A non-reference parameter is a new local object, while an lvalue-reference parameter is an alias…
- A.
(a) only
- B.
(b) only
- C.
(c) only
- D.
(b) and (c) only
Attempted by 180 students.
Show answer & explanation
Correct answer: B
Concept
A function parameter is initialized from its argument. A non-reference parameter is a new local object, while an lvalue-reference parameter is an alias for an existing object.
A pointer passed by value is also a local copy. It can modify the pointed-to object only through dereferencing; assigning the pointer variable itself merely changes that local copy.
Application
For
void swap(int a, int b), begin with local copiesa = 0andb = 1. Aftertemp = a; a = b; b = temp;the locals becomea = 1andb = 0, but the caller’s objects are not aliases of these locals.For
void swap(int &a, int &b),aaliasespandbaliasesq. The same assignments write1intopand0intoq.For
void swap(int *a, int *b), the callswap(&p, &q)creates local pointer copies. The assignments exchange only those local addresses because neither*anor*bis assigned.
Cross-check
After each call, inspect caller storage: the value-parameter form leaves p = 0, q = 1; the reference-parameter form leaves p = 1, q = 0; and the shown pointer-parameter form again leaves p = 0, q = 1.
Result
Only the reference-parameter implementation, void swap(int &a, int &b), swaps the contents of p and q.
A video solution is available for this question — log in and enroll to watch it.