C++ program for call by value
kw.cpp
#include <iostream>
using namespace std;
int add(int a, int b)
{
    a = 100;
    b = 100;
    int c = a + b;
    return c;
}
int main()
{
    int a = 20, b = 10, c;
    c = a + b;
    add(a, b);
    cout<<c<<endl;
}
Output
kodingwindow@kw:~$ g++ kw.cpp
kodingwindow@kw:~$ ./a.out 30 kodingwindow@kw:~$
C++ program for call by reference
kw.cpp
#include <iostream>
using namespace std;
void swap(int *a, int *b)
{
    int c;
    c = *a;
    *a = *b;
    *b = c;
}
int main()
{
    int a = 10, b = 20;
    swap(&a, &b);
    cout<<"a="<<a<<endl;
    cout<<"b="<<b<<endl;
    return 0;
}
Output
kodingwindow@kw:~$ g++ kw.cpp
kodingwindow@kw:~$ ./a.out a=10 b=20 kodingwindow@kw:~$
Advertisement