Sunday, March 30, 2014

CPP Program to demonstrate how to call function by reference

CPP Program : how to call function by reference


Calling by reference is new concept which is not available in C language. It is not passing address just like in C. but it is giving another name to an existing variable, just like an alias. Don't mistake this as call by reference in C. In C call by reference and call by address is same thing. But in CPP both are different, having some similarities. Call by reference is simpler than call by address. But you cannot use reference all the place you are using address. This concept is clear from the following example

#include<conio.h>
#include<iostream>
using namespace std;
int addition (int &a, int &b)// declaration of called function using & sign
{
int y;
y=a+b;
return (y);
}
int main()
{
int x,y,sum;
//clrscr();
cout<<"Enter two integers to be added\n";
cin>>x>>y;
sum=addition(x,y);// calling function just like calling function by value
cout<<"Sum of the integers="<<sum;
getch();
return 0;
}

No comments:

Post a Comment