Call By Value and Call By Reference in C++ Function


Call By Value

Syntax

return_type function_name( param_1,param_2 ... param_n );

For example,

int swap(int x,int y)

Call By Value Example Program in C++

//Simple Call By Value Function Example Program in C++
//Function Example

#include<iostream>
#include<conio.h>

using namespace std;

void swap(int x, int y);

int main() {
   int a = 200, b = 100;
   cout << "Simple Call By Value Function Example Program\n";
   swap(a,b);
   cout << "\nValues (Main  )  a :"<<a<<" b:"<<b;

   getch();
}

// Call By Value Function
void swap(int x, int y) {
  int t;
  t = x;
  x = y;
  y = t;
  cout << "\nValues (Function) x :"<<x<<" y:"<<y;
}

Sample Output

Simple Call By Value Function Example Program

Values (Function) x :100 y:200
Values (Main  )  a :200 b:100

Call By Reference

Syntax

return_type function_name( *param_1,*param_2 ... param_n );

For example,

int swap(int *x,int *y)

Call By Reference Example Program  in C++

//Simple Call By Reference Function Example Program in C++
//Function Example

#include<iostream>
#include<conio.h>

using namespace std;

void swap(int *x, int *y);

int main() {
   int a = 200, b = 100;
   cout << "Simple Call By Reference Function Example Program\n";
   swap(&a,&b);
   cout << "\nValues (Main  )  a :"<<a<<" b:"<<b;

   getch();
}

// Call By Reference Function
void swap(int *x, int *y) {
  int t;
  t = *x;
  *x = *y;
  *y = t;
  cout << "\nValues (Function) x :"<<*x<<" y:"<<*y;
}

Sample Output

Simple Call By Reference Function Example Program

Values (Function) x :100 y:200
Values (Main  )  a :100 b:200