< Previous | Contents | Next >
The first thing I do in main() is create a variable to hold my score.
int myScore = 1000;
Then I create a reference that refers to myScore.
int& mikesScore = myScore; //create a reference
The preceding line declares and initializes mikesScore, a reference that refers to myScore. mikesScore is an alias for myScore. mikesScore does not hold its own int value; it’s simply another way to get at the int value that myScore holds.
To declare and initialize a reference, start with the type of value to which the reference will refer, followed by the reference operator (&), followed by the reference name, followed by =, followed by the variable to which the reference will refer.
Tric k
Sometimes programmers prefix a reference name with the letter “r” to remind them that they’re working with a reference. A programmer might include the following lines:
int playerScore = 1000; int& rScore = playerScore;
One way to understand references is to think of them as nicknames. For example, suppose you’ve got a friend named Eugene, and he (understandably) asks to be called by a nickname—Gibby (not much of an improvement, but it’s what Eugene
190 Chapter 6 n References: Tic-Tac-Toe
wants). So when you’re at a party with your friend, you can call him over using either Eugene or Gibby. Your friend is only one person, but you can call him using either his name or a nickname. This is the same way a variable and a reference to that variable work. You can get to a single value stored in a variable by using its variable name or the name of a reference to that variable. Finally, whatever you do, try not to name your variables Eugene—for their sakes.
Tra p
Because a reference must always refer to another value, you must initialize the reference when you declare it. If you don’t, you’ll get a compile error. The following line is quite illegal:
int& mikesScore; //don’t try this at home!