Program to perform Call by Value

Following is the program to perform call by value.

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

void swap(int a, int b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}

int main()
{
    int a = 100, b = 200;
    clrscr();
    swap(a, b);  // passing value to function
    cout<<"Value of a"<<a;
    cout<<"Value of b"<<b;
    getch();
    return 0;
}

Value of a: 100 Value of b: 200

As you can see in the output, although we swapped the values of variable a and b inside the function swap() still in the main() method those changes are not passed on.


Program to perform Call by Reference

Following is the program to perform call by reference.

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

void swap(int &a, int &b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}

int main()
{
    int a = 100, b = 200;
    clrscr();
    swap(a, b);  // passing value to function
    cout<<"Value of a"<<a;
    cout<<"Value of b"<<b;
    getch();
    return 0;
}

Value of a: 200 Value of b: 100