There are three ways that are used to pass variables to a function in c++, pass by value, pass by reference and pass by pointer.

(1) pass by value

#include<iostream>
using namespace std;

int foo(int a, int b);

int main()

{
    cout<<foo(4,3)<<endl;
return 0;
}

int foo( int a, int b)
{
    return ( a + b);
}

let us consider another example:

#include<iostream>
using namespace std;

void swap(int a, int b);

int main()

{

 int a=3;
 int b=4;

 swap(a,b);
 cout<<"a="<<a<<"\t"<<"b="<<b<<endl;
 return 0;
}

void swap( int a, int b)
{
 int temp;
 temp = a; /* store the value of a to temp */
 a = b; /* assign b into a */
 b = temp; /* assign a into b */
}
The output of above program will be: a=3	b=4
This shows that passing variable by value creates a separate copy and does not affect actual variables. also it consumes memory.

(2) pass by reference

passing variables by reference or pointer avoid creation of new variables. also it affects the actual variables.

#include<iostream>
using namespace std;

void swap(int& a, int& b);

int main()

{

int a=3;
int b=4;

swap(a,b);
cout<<"a="<<a<<"\t"<<"b="<<b<<endl;
return 0;
}

void swap( int& a, int& b)
{
int temp;
temp = a; /* store the value of a to temp */
a = b; /* assign b into a */
b = temp; /* assign a into b */
}
output:
a=4    b=3

(3) pass by pointer

#include<iostream>
using namespace std;

void swap(int* a, int* b);

int main()

{

int a=3;
int b=4;

swap(&a,&b);
cout<<"a="<<a<<"\t"<<"b="<<b<<endl;
return 0;
}

void swap( int* a, int* b)
{
int temp;
temp = *a; /* store the value of a to temp */
*a = *b; /* assign b into a */
*b = temp; /* assign a into b */
}
output:
a=4    b=3


Related Contents to follow