what is call by value and call by reference in c++

what is call by value and call by reference in c++



call by value:


In call by value,do not change or modify original value because if we will change the value so that time of course change the value but in main() function do not except this value because old value is already store in stack memory.

For Ex.
coding:


#include<iostream>

using namespace std;
//call by value
void swap (int x, int y)
{
  int temp;
  temp = x;
  x = y;
  y = temp;
}

int main()
{
 int x = 4,y = 7;
 cout << "Before Swap:" << endl;
 cout << "x=" << x << "\ty=" << y << endl;
 swap (x, y);
 cout << "After Swap:" << endl;
 cout << "x=" << x << "\ty=" << y;
}


output :


call by reference:

In call by reference,we change or modify the value because we pass address .address pass in the function,so  actual and formal arguments shares the same address space. Hence, any value changed inside the function, is reflected inside as well as outside the function. 

For Ex,
coding:

#include<iostream.h>

void swap(int *x, int *y)
{
 int temp;
 temp=*x;
 *x=*y;
 *y=temp;
}

void main() 
{  
 int a=20, b=50;  
  swap(&x, &y);  // passing value to function
 cout<<"Value of a"<<a;
 cout<<"Value of b"<<b;
 }  

output:


0 comments:

Copyright © 2013 free coding