3,721 views

Given below are three implementations of the $\text{swap()}$ function in $\text{C++}$ :

$\begin{array}{|l|l|l|} \hline \qquad \qquad \text{(a)} & \qquad \qquad \text{(b)} & \qquad \qquad \text{(c)} \\ \text{void swap (int a, int b)} & \text{void swap (int &a, int &b)} & \text{void swap (int *a, int *b)} \\ \text{\{} & \text{\{} & \text{\{} \\ \text{int temp;} & \text{int temp;} & \text{int *temp;} \\ \text{temp = a;} & \text{temp = a;} & \text{temp = a;} \\ \text{a = b;} & \text{a = b;} & \text{a = b;} \\ \text{b = temp;} & \text{b = temp;} & \text{b = temp;} \\ \text{\}} & \text{\}} & \text{\}} \\ \text{int main()} & \text{int main()} & \text{int main()} \\ \text{int p = 0,q = 1;} & \text{int p = 0, int q = 1;} & \text{int p = 0 , q = 1;} \\ \text{swap(p,q);} & \text{swap(p,q);} &\text{swap(p,q);} \\ \text{\}} & \text{\}} & \text{\}}\\\hline \end{array}$

Which of these would actually swap the contents of the two integer variables $\text{p}$ and $\text{q}$?

1. $\text{(a)}$ only
2. $\text{(b)}$ only
3. $\text{(c)}$ only
4. $\text{(b)}$ and $\text{(c)}$ only

### 1 comment

c only..!

Option (2) Only B is Correct.

Implementation 'a' swaps the values of a and b inside swap() but p and q remain unchanged in main().

Implementation 'b' swaps the the memory location of a and b (to which they are pointing to) inside swap(), hence p and q also get swapped in main().

Implementation 'c' is almost similar to 'a'. Though temp is a pointer to an integer, still, it swaps the values of a and b (and not the memory locations to which a and b are pointing to) inside swap() but p and q remain unchanged in main().

PS: One may want to try compiling all the three implementations in C++ and conclude the answer.