Reference
Call by value
Call by address
Call by reference
Call by value​
Example 1:
// call by value
#include <iostream>
using namespace std;
void fun(int num)
{
num = num + 2;
cout<<"Inside function "<<num<<endl;
}
int main() {
int num = 10,
cout<<"Before function :"<<num<<endl;
fun(num);
cout<<"After function :"<<num<<endl;
return 0;
}
Output :
Before function : 10
Inside function : 12
After function : 10
Expalantion
create function fun
pass parameter num
.
calculate num = num + 2
.
print Inside function
and num
.
In main function initialize num
variable and store 10
value.
print Before function
and num
.
call fun
funaction pass argument num
.
print After function
and num
.
Call by address​
Example 2:
//call by address
#include <iostream>
using namespace std;
void fun(int *num)
{
*num = *num + 2;
cout<<"Inside function :"<<*num<<endl;
}
int main() {
int num = 10
cout<<"Before function :"<<num<<endl;
fun(&num);
cout<<"After function "<<num<<endl;
return 0;
}
Output :
Before function : 10
Inside function : 12
After function : 10
Expalantion
create function fun
pass parameter *num
.
calculate *num = *num + 2
.
print Inside function
and *num
.
In main function initialize num
variable and store 10
value.
print Before function
and &num
.
call fun
funaction pass argument num
.
print After function
and num
.
Call by reference​
Example 3:
//call by reference
#include <iostream>
using namespace std;
int main() {
int a = 10;
int& b = a;
cout<<a<<endl;
cout<<b;
return 0;
}
Output :
10
10
Expalantion
Initialise a
variable and store 10
value.
Initialise b
variable and store refrence of a
.
print a
endl
for new line.
print b
.