Thursday 28 March 2019

UGC NET Computer Science July 2018 - II | Question 5

Question 5
5. 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. (1) (a) only
  2. (2) (b) only
  3. (3) (c) only
  4. (4) (b) and (c) only
Answer : (2) (b) only
Explanation Question 5

  • 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


PreviousNext
UGC-NET CS 2018 July - II Question 4UGC NET CS 2018 July - II Question 6

No comments:

Post a Comment

UGC NET Computer Science December 2019 | Question 16

Question 16 In a certain coding language. 'AEIOU' is written as 'TNHDZ'. Using the same coding language. 'BFJPV' wil...

Popular Posts