Saturday, August 29, 2009

Functions: Parameter-passing mechanisms

The simplest parameter-passing mechanism in C++ occurs by default. It is called call-by-value. Value passed using this method are called value parameters. Any modification of a value parameter within the function body has no effect on the value of its corresponding argument:

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


Previous post

Next post




No comments:

Post a Comment