Sunday 8 December 2013

Function by Reference

#include <iostream>
using namespace std;
void swap(int &a, int &b);
int main ()
{
  int a,b,z;
  cout<<"Enter First Number"<<endl;
  cin>>a;
  cout<<"Enter Second Number"<<endl;
  cin>>b;
  cout<<"Numbers before Swapping"<<endl;
  cout<<a<<endl<<b<<endl;
  swap(a,b);
  cout<<"Numbers after Swapping"<<endl;
  cout<<a<<endl<<b<<endl;
}
void swap(int &a, int &b)
{
int c;
c=a;
a=b;
b=c;
}

In this,we will discuss sending data by reference......!!
But,First you will knowm what the difference b/w Calling function by Value and
Calling function by Reference......!!
Call by Value:-
1)Call by value passes the value of actual parameter to formal parameter
2)The actual and formal parameters refer to different memory locations.
3)Any change made by function in formal parameter does not affect the value of Actual parameter.
4)It Requires more Memory.
5)It is less Efficient.
Call By Reference:-
1)Call by Reference passes the address of actual parameter to formal parameter.
2)The actual and formal parameters refer to same memory locations.
3)Any change made by function in formal parameter actually changes the value of Actual parameter.
4)It Requires Less Memory.
5)It is more Efficient.

Now,I think you known Whats the difference b/w..............!!!
In this program,we will simply geting two numbers from users and then displaying it,and afterthat we call the function swap() and it will swap these two numbers(mean a is put to b and b is put to a).......!!!
Note:-
If you want to type your function after main,then you will always tell the compiler that a function name this will be using in this program like in this case....!!
What the swap() function is doing.....??
We will send int a,b to it,but on other side(function side) there are pointers which will save there addresses respectively........!!
And its done...!
If we give,
a=2;
b=3;
After swapping it will be,
a=3;
b=2;


I think you got it.........!!!

Feel free to give suggestions in comment box.......! 

0 comments: