in Object Oriented Programming edited by
3,721 views
1 vote
1 vote

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
in Object Oriented Programming edited by
3.7k views

1 comment

c only..!
0
0

6 Answers

0 votes
0 votes
Option (2) Only B is Correct.
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

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true