Passing Values in C++ :
Passing Values in C++ :
There are many ways to get values in and out of functions in c++.
Data is passed into functions or routines via arguments. These arguments can be classified into call-by-value and call-by-reference.
• To call-by-value means to pass only the value of the data (a copy).
• To call-by-reference means to pass the reference of the data.
Here is a simple example to explain the difference between Call by Value and Call by reference.
Call by Value :
#include
using namespace std;
int double_fun(int m) { // i passed by value
m=m*2;
return m;
}
int main() {
int i=5;
int j = double_fun(i);
coutIn above example, while calling double_fun(i) argument value itself passed, So finally the value of “i” will be 5 after calling the fuction “double_fun()” and the value of “j” will be 10 which will be calculated and returned from double_fun.
Call by Reference :
#include
using namespace std;
int double_fun(int &m) { // i passed by reference, note the ambersand
m=m*2;
return m;
}
int main() {
int i=5;
int j = double_fun(i);
coutIn above example the value of “i” will be 10 after calling “double_fun()” function.
Note the only difference between above 2 programs is,
int double_fun(int &m) {
the above line will pass the reference of “m” variable. In double function m value will be doubled and returned. So the value of i will become 10.
Alias :
Call-by-reference parameter passing is one way that aliasing can be introduced. Aliasing is when multiple variables share a single value–changes to one mean all of the variables change.
