Call By Value

In call by value, value of variable is passed during function call.

And copy this value in another variable at function definition

.In call by value the original value in calling function wil

l never change after execution of function.

Example:

#include<iostream>

using namespace std;

void swp(int a, int b)

{

int temp=a;

a=b;

b=temp;

}

int main()

{

int x,y;

cout<<"enter value of a and b:";

cin>>x>>y;

swp(x,y);

cout<<”

nafter swapping a = ”<<a<<”and b = ”<<b;

return 0;

}

Output:

Enter value of a and b:

4

5

After swapping a = 5 and b = 4

 

Call By Reference

In call by reference, reference is passed during function call.

The formal arguments in the called function become aliases to the actual function call.

In call by reference the original value in calling function will change after execution of function.

Example:

#include<iostream>

using namespace std;

void swap(int &a, int &b) // It is the only difference from above program

{

int temp=a;

a=b;

b=temp;

}

int main()

{

int a,b;

cout<<"Enter two numbers:";

cin>>a>>b;

swap(a,b);

cout<<"a="<<a<<"b="<<b;

return 0;

}

Output:

Enter value of a and b:

4

5

After swapping a = 5 and b = 4