The Gateway to Computer Science Excellence
0 votes
790 views

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

a b c
void swap (int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int main()
{
int p=0, q=1;
swap(p, q);
}
void swap (int &a, int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int main()
{
int p=0, q=1;
swap(p, q);
}
void swap (int *a, int *b)
{
int *temp;
temp=a;
a=b;
b=temp;
}
int main()
{
int p=0, q=1;
swap(&p, &q);
}

Which of these would actually swap the contents of the two integer variables p and q?

  1. a only
  2. b only
  3. c only
  4. b and c only
in Others by Boss (10.8k points)
retagged by | 790 views
0
c only..!

2 Answers

+1 vote
Only C.

A performs the swap on the local variables - the original variables are not changed.

B is incorrect declaration.

C is the only one which swaps correctly.
by Loyal (6.5k points)
+1

I also answered 'C' but official key show 'B' is the correct...
Can you explain ?
 

Official answer key
Caption

 

0
I don't think so that option (b) is incorrect declaration
Rather part (c) is incorrect because inside swap function definition there is incorrect assignment of values at the addresses of a and b

Thus answer should be option 2 i.e (b) only

If I am wrong then please correct me
+1 vote
It is not asked for c, it is asked for c++ and in c++ &a=b implies somewhat like pointer thing but not pointer. Hence B is correct option.moreover option c is incorrect as it is swapping pointers not the values.
by (29 points)

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
50,647 questions
56,459 answers
195,377 comments
100,270 users