Monday, 4 February 2013

List the uses of references

Defination:
giving synonym to the existing variable is called reference variable.

Example:
int a=5;
int &b=a;
List the uses of references.
Ans:
        Ans: /*see the notes for advantages of reference variable. This question is most frequently asked question in Interviews > 
1) Fast Execution 2) Saving Memory 3) We can avoid the pointers 4) duplication is avoided
5) No complexity

Where do we use Reference?

when you have to pass a class object as an argument to any function. when you want to modify the data in the calling function through called function. 2) in copy constructor

#include <iostream>
#include<conio.h>
void swap(int &a, int &b)
{
    int temp = 0;
    temp = a;
    a = b;
    b = temp;

    return;
}

void main()
{
   int a = 10;
   int b = 20;

   cout<< "\na = "<< a <<"\n"<<"b = "<<b<<"\n";

   swap(a,b);

   cout<< "After swap";
   cout<< "\na = "<< a <<"\n"<<"b = "<<b<<"\n";


}

same program using Pointers

#include <iostream.h>
#include<conio.h>
void swap(int *a, int *b)
{
    int temp = 0;
    temp = *a;
    *a = *b;
    *b = temp;
    
}

void main()
{
   int a = 10;
   int b = 20;

   cout<< "\na = "<< a <<"\n"<<"b = "<<b<<"\n";

   swap(&a,&b);

   cout<< "After swap";
   cout<< "\na = "<< a <<"\n"<<"b = "<<b<<"\n";
   getch();

}

some points about reference variable:


  • Do not initialize a reference variable with a constant value. This means int &var = 10 is not a valid initialization.
  • Do not return a reference from a function as the memory address that is referred by the reference variable would scope out once the function is done it’s execution.
  • Avoid using references to variables whose memory are dynamically allocated as it might create unnecessary confusion regarding the clean-up of that memory.plexity (6) It allows parameter to be changed .

No comments:

Post a Comment