How To Pass Parameters To A Function – By Value, By Reference
Function parameters are passed by value. This means that parameters are
variables which are assigned the values of the arguments used when a function
is called.
For example, given the function definition:
int multiplyByTwo(int a)
{
a = a * 2;
return a;
}
if the function is called for example the following way:
int x = 6;
multiplyByTwo(x);
The value of
x is assigned to
a, then
a is
assigned
a * 2 and finally
a is returned. But the original value of
x will not change (in this case it will still
be
6).
In case you want the original argument passed to a function to be modifiable by
the function's statements, you can pre-pone the parameter's name with a
&:
int multipyByTwoCallByReference(int &b)
{
b = b *2;
return b;
}
in this case the original argument would get doubled.
Another way to pass an argument by reference is to pass a pointer:
int multiplyByTwoPointerReference(int *pint)
{
*pint = *pint * 2;
return *pint;
}
In this case the variable located at the address
pint is modified.
Finally, a function can also return a pointer. The pointer, though, mustn't
contain the address of a local variable or formal parameter, because they
get destroyed at the function’s exit.
int *multiplyByTwoPointerReference2(int *pint)
{
*pint = *pint * 2;
return pint;
}
Example
#include <iostream>
using namespace std;
int multiplyByTwo(int a)
{
a = a * 2;
return a;
}
int multipyByTwoCallByReference(int &b)
{
b = b *2;
return b;
}
int multiplyByTwoPointerReference(int *pint)
{
*pint = *pint * 2;
return *pint;
}
int *multiplyByTwoPointerReference2(int *pint)
{
*pint = *pint * 2;
return pint;
}
int main()
{
int x = 3;
int *pinteger;
cout << "x is: " << x << endl;
cout << "multiplyByTwo(x); returns " << multiplyByTwo(x) << endl;
cout << "x is: " << x << endl;
cout << "x is: " << x << endl;
cout << "multipyByTwoCallByReference(x); returns " << multipyByTwoCallByReference(x) << endl;
cout << "x is: " << x << endl;
cout << "x is: " << x << endl;
cout << "multiplyByTwoPointerReference(&x); returns " << multiplyByTwoPointerReference(&x) << endl;
cout << "x is: " << x << endl;
cout << "x is: " << x << endl;
cout << "multiplyByTwoPointerReference2(&x); returns " << (pinteger = multiplyByTwoPointerReference2(&x)) << endl;
cout << "x is: " << x << endl;
cout << "*pinteger is: " << *pinteger << endl;
}
Output
x is: 3
multiplyByTwo(x); returns 6
x is: 3
x is: 3
multipyByTwoCallByReference(x); returns 6
x is: 6
x is: 6
multiplyByTwoPointerReference(&x); returns 12
x is: 12
x is: 12
multiplyByTwoPointerReference2(&x); returns 0012F4CC
x is: 24
*pinteger is: 24