Function Call by Reference in C++

There are two types of function calling , call by values and call by reference. In function call by reference we declare the function parameters by reference instead of normal variables. Inside the function ,the reference is used to access the actual parameters used in call.In this example we swap the two integers with call by reference function.

Source Code

#include<iostream>
using namespace std;
void swap (int &a , int &b);
int main ()
{
 int num1,num2;
 char c;
 cout<<"\t \t \t LEP Tutorials \n ";
 cout<<" Enter Your 1st Number : ";
 cin>>num1;
 cout<<"  Enter Your 2nd Number : ";
 cin>>num2;
 cout<<"\t  Do You Want to Swap these Values ? Y/N ";
 cin>>c;
 if ( c =='y' || c== 'Y')
 {
  swap (num1,num2);
  cout<<" After Swap 1st Number :"<<num1;
  cout<<endl;
  cout<<" After Swap 2nd Number :"<<num2;
  cout<<endl;
 }
 else
 {
  return 0;
 }
}
void swap (int &a, int &b)
{
 int temp ;
 temp = a;
 a = b;
 b = temp;
}

Output of the Program

Function call by reference in C++

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment