When you pass by value to a function (for example), it will copy the value stored in the variable you pass and if you change the copied variable it will not change the variable in the function that called the function.
However, when you pass by reference, you pass the address of variable, rather then the variable itself. So when you change the variable in the function, it WILL be changed in the function that called this function.
Since whenever you have probably used a function with parameters, I wont show how to pass by value, as that is what happens when you call a function with parameters. But I will show you the code to pass by reference and then explain it.
void TestFunction(int &variable1)
{
variable1 = 1337;
}
All I have done it put a & in front of the passed variable declaration. So if we had something like this:
#include <cstdlib>
#include <iostream>
using namespace std;
void TestFunction(int &variable1)
{
variable1 = 1337;
}
int main(int argc, char *argv[])
{
int a;
a = 7;
TestFunction(a);
cout << a << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
It will print the number 1337, because we called TestFunction, however if we A) Didn't call TestFunction or B) Did not put the & in front of variable1 - it would just print 7.


Sign In
Create Account


Back to top









