All mock tests are FREE till 31 December — register to save your progress

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

(a) void swap(int a, int b) { int temp; temp = a; a = b; b = temp; }  called as swap(p, q);
(b) void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; }  called as swap(p, q);
(c) void swap(int *a, int *b) { int *temp; temp = a; a = b; b = temp; }  called as swap(&p, &q);

with int p = 0, q = 1 in main(). Which of these would actually swap the contents of p and q?

Pick an option to check yourself, or open the answer below.

Show answer & explanation

Correct answer: B. (b) only

Explanation

(a) swaps copies. (b) swaps through references, so p and q change. (c) swaps only the local pointer copies, never *a and *b, so p and q are untouched.

More Programming Languages and Computer Graphics questions