void divideByTwo( int parameter )
{
parameter = parameter / 2;
}
int main( void )
{
int figure = 42;
divideByTwo( figure );
cout << figure << endl;
return EXIT_SUCCESS;
}
prints 42 as a result.
It would be often useful to be able to change the value of the corresponding argument. For example, if the function needs to return more than one value, data could be returned by changing the value of the parameters. There is also call-by-reference mechanism in C++. These parameters are called reference parameters. Reference parameters are aliases of their corresponding arguments, i.e. any change to the value of a reference parameter within the function body changes the value of its corresponding argument. When using call-by-reference, the values are passed by adding an ampersand (&) between the type and the name of the parameter.
The example mentioned before:
void divideByTwo( int& parameter )
{
parameter = parameter / 2;
}
int main( void )
{
int figure = 42;
divideByTwo( figure );
cout << figure << endl;
return EXIT_SUCCESS;
}
prints now 21, i.e. function divideByTwo was able to change the actual value of the parameter.
Reference: msdn, comp, brpreiss
No comments:
Post a Comment