Parameter Passing



Parameter Passing Mechanisms in C++

There are two ways to pass parameters:


Pass by Value

In the case of passing parameters by value, the formal parameters of a function are copies of the actual parameters' values. This means that:


Example:

#include < iostream >
using namespace std;

int gcd(int a , int b)
{
    cout << "At the start of the gcd function, a = " << a << " and b = " << b << endl;
    while(b != 0)
    {
        int r = a % b;
        a = b;
        b = r;
    }
    cout << "At the end of the gcd function, a = " << a << " and b = " << b << endl;
    return a;
}

int main()
{
    int x = 24, y = 18;
    cout << gcd(x , y) << endl;
    cout << "After calling the gcd function, x = " << x << " and y = " << y << endl;
    return 0;
}

We observe that although the formal parameters a and b in the gcd function are modified, in main(), after calling the gcd function, the actual parameters x and y have their original values.


Pass by Reference

This is the specific C++ mechanism by which we can modify variables outside the function within the function. In the case of passing parameters by reference, the formal parameters of a function are references to the actual parameters. This means that:


Example:

#include < iostream >
using namespace std;

void doubleValue(int & n)
{
    n = 2 * n;
}

int main()
{
    int x = 24;
    cout << "x = "  << x << endl;
    doubleValue(x);
    cout << "x = "  << x << endl;
    return 0;
}

We observe that, upon exit from the call, the value of the variable x is modified. Moreover, a call like doubleValue(10); represents a syntax error, because the actual parameter must be a variable.


Accessibility Options

Color Contrast

Text Size

Text Spacing

Reading Aids