When passing pointers, it can often become annoying to constantly add * to every variable whose address you're passing. And now, behold -- It's time to learn how you can pass addresses and have them seem to be a normal variable! C++ has a special kind of variable called a reference variable. This variable must be given an variable when it's created that it can point at. However, once this is done, it acts just like a pointer; since it just points to another variable, when you change that variable, you're changing this one, and vice-versa. So, how do we use this marvelous super-variable, you ask? Simple! This is how it's declared in a program: int fajita; int &beans=fajita; void taco(double &nacho) Notice that we declared a regular int before declaring the reference-to-int beans? The reason for this is that references variables must always be assigned a value to point at when they are declared; so, we gave it something to make a reference to. Also you may note that we don't give nacho a value when it's declared. That's ok, because we give it a value when we pass parameters to its function. Let's put the pieces together and try using a reference variable in a program: #include <iostream.h> /* Improves a taco's rating */ void enhance_taco(int &taco) { taco = 10; /* Mmm, tacos */ } void main(void) { int unyummytaco; int yummytaco; int &taco=yummytaco; unyummytaco = 1; yummytaco = 9; cout << "Yummy Taco is " << yummytaco << "\n"; cout << "Un-Yummy Taco is " << unyummytaco << endl; cout << "Reference Variable Taco is " << taco << endl; cout << "\nRunning the Magic Taco Enhancer..\n\n"; enhance_taco(yummytaco); enhance_taco(unyummytaco); cout << "Yummy Taco is " << yummytaco << "\n"; cout << "Un-Yummy Taco is " << unyummytaco << endl; cout << "Reference Variable Taco is " << taco << endl; } Here's what the program prints out: Yummy Taco is 9 Un-Yummy Taco is 1 Reference Variable Taco is 9 Running the Magic Taco Enhancer.. Yummy Taco is 10 Un-Yummy Taco is 10 Reference Variable Taco is 10
Look at the output -- the reference variable has the same as the yummy taco
variable! By saying "
Also note how the function
You may see this as markedly similar to value parameters in Pascal.
It is, and if you are having troubles with pointers in C++, think of
|