edited by
4,595 views
1 votes
1 votes

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
edited by

6 Answers

0 votes
0 votes

Answer: (B)

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.

Related questions

1 votes
1 votes
2 answers
2
Pooja Khatri asked Jul 13, 2018
2,655 views
The definitions in an XML document are said to be ______ when the tagging system ans definitions in the DTD are all in compliancewell-formedreasonablevalidlogical