There are two ways to pass parameters:
In the case of passing parameters by value, the formal parameters of a function are copies of the actual parameters' values. This means that:
#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.
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:
#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.
In this section you can generate a summary of the page content using AI! Feel free to use the button below whenever you are in a hurry and don't have time to learn everything!
In this section you can ask our expert robot anything related to the questions you encountered during the lessons! Feel free to use the button below whenever you need additional explanations!