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?

Answer: B. (b) onlyConceptA function parameter is initialized from its argument. A non-reference parameter is a new local object, while an lvalue-reference parameter is an alias…

  1. A.

    (a) only

  2. B.

    (b) only

  3. C.

    (c) only

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

  1. For void swap(int a, int b), begin with local copies a = 0 and b = 1. After temp = a; a = b; b = temp; the locals become a = 1 and b = 0, but the caller’s objects are not aliases of these locals.

  2. For void swap(int &a, int &b), a aliases p and b aliases q. The same assignments write 1 into p and 0 into q.

  3. For void swap(int *a, int *b), the call swap(&p, &q) creates local pointer copies. The assignments exchange only those local addresses because neither *a nor *b is 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.

Explore the full course: Tpsc Assistant Technical Officer

Loading lesson…