Hello DarkParadox,
After all that good reading it boils down to pass by value or pass by reference.
In the first example
void x(int a,int b)
This is pass by reference and "a" and "b" represent a copy of the original variables used to call the function. As a copy when the function ends so do the copies and the original calling variables know nothing of any changes that the function made. A simple program to illustrate this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
void x(int a, int b);
int main()
{
int row{ 0 };
int col{ 0 };
char end{ ' ' };
x(row, col);
std::cout << "\n row = " << row << "\n col = " << col << std::endl;
//std::cin >> end;
std::cin.get();
return 0;
}
void x(int a, int b)
{
a++;
b++;
}
|
Notice how "row" and "col" do not change.
The example
void x(int& a,int& b)
is pass by reference. In this case "a" and "b" become new names for "row" and "col" and any changes in in the function to "a" and "b" are reflected back in main for the variables "row" and "col".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
void x(int& a, int& b);
int main()
{
int row{ 0 };
int col{ 0 };
char end{ ' ' };
x(row, col);
std::cout << "\n row = " << row << "\n col = " << col << std::endl;
std::cin >> end;
return 0;
}
void x(int& a, int& b)
{
a++;
b++;
}
|
Notice how "row" and "col" have changed in main.
Advantages to pass by reference are that sometimes it is easier than making a copy of something large, less overhead than making the copy, and you have direct access to the variable that was passed in. Since a function can only return one of anything passing variables by reference allows you to change more than one variable with the function and when the function ends changes are made to the original variables before the local variables of the function are lost.
Should you not want to change the original variables just make them "const" in the function parameters.
That cover most of the major points, but I feel I have missed some of the minor points.
Hope that helps,
Andy
P.S. be sure to run the programs.