Normal function arguments are passed by "value", just a copy of the value of the variable is passed :
1 2 3 4 5 6 7 8 9 10 11
|
void printANumber ( int number ) // the parameter type doesn't have '&' sign, it is passed by value
{
cout << number;
}
// ...
// ...
int main ()
{
int x = 100; // declare a variable
printANumber ( x ); // here we passed the value of x which is 100
}
|
You can visualize what happens when calling the function :
1 2 3 4
|
printANumber ( int number = x ) // number becomes 100
{
cout << number; // 100 is printed
}
|
----------------------------------------------------
Whereas when a function takes an argument as reference, *the variable is passed*, not just the value, so we can modify it inside the function :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void changeANumber ( int& number ) // notice the '&' sign, it is passed by reference
{
number = 243; // change the value of the variable passed
}
// ...
// ...
int main ()
{
int x = 978;
cout << x; // 978 is printed;
changeANumber ( x ); // we passed the variable x, not 978
cout << x; // 243 is printed, since the variable x is passed not the value of it
}
|
------------------------------------------------------
Why do we use the rX and rY in the prototype and the function body, but just x and y when declaring the variables and in the function call |
rX and rY are, yes, they are different from x and y, rX and rY are called function parameters, they are variables that can hold the values of the variables passed as parameter when calling the function. but since askForXandY() takes a reference argument, the variables x and y are passed :
let's test your code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
void AskForXandY(int &rX, int &rY)
{
cout << "Enter X and Y";
cin >> rX >> rY; // let's say i enter 23 and 45
}
// ...
// ...
int main()
{
int x = 0, y = 0;
cout << x << " " << y << endl; // 0 0 is printed
AskForXandY(x, y);
cout << x << " " << y; // print the value of x and y
// The values printed are 23 45 !
}
|
JUst ask if you have more questions