Question 5
5. Given below are three implementations of the swap( ) function in C++ :
Which of these would actually swap the contents of the two integer variables p and q ?
Answer : (2) (b) only
Which of these would actually swap the contents of the two integer variables p and q ?
Explanation Question 5
Hence, implementation (b) reflects the swapped value to the passed variable.
So, option (2) is right answer.
Function implementation to swap values using pass by reference without pointer:
Function implementation to swap values with pass by reference using pointers:
Reference : Example 1: Passing by reference without pointers
- Implementation (a) performs the swap on the local variables. So, the original variables are not changed.
- 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(). Swap() function is accepting the alias of the variable (int &a) - it will evaluate parameter as int &a=p;. To swap values implementation (b) uses pass by reference without pointers.
- Implementation (c) is incorrect because inside swap function definition there is incorrect assignment of values at the addresses of a and b.
Hence, implementation (b) reflects the swapped value to the passed variable.
So, option (2) is right answer.
Function implementation to swap values using pass by reference without pointer:
void swap(int &n1, int &n2) {
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
Function implementation to swap values with pass by reference using pointers:
void swap(int* n1, int* n2) {
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Reference : Example 1: Passing by reference without pointers
Previous | Next |
UGC-NET CS 2018 July - II Question 4 | UGC NET CS 2018 July - II Question 6 |
int temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int p = 0, q = 1;
swap(p, q);
}
int temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int p = 0, q = 1;
swap (p, q);
}
int * temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int p = 0, q = 1;
swap (&p, &q);
}