< Previous | Contents | Next >

Introducing the Referencing Program

The Referencing program demonstrates references. The program declares and initializes a variable to hold a score and then creates a reference that refers to the variable. The program displays the score using the variable and the reference to


187

188 Chapter 6 n References: Tic-Tac-Toe


show that they access the same single value. Next, the program shows that this single value can be altered through either the variable or the reference. Figure 6.1 illustrates the program.



image

Figure 6.1

The variable myScore and the reference mikesScore are both names for the single score value.


You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 6 folder; the filename is referencing.cpp.

// Referencing

// Demonstrates using references #include <iostream>

using namespace std;


int main()

{

int myScore = 1000;

int& mikesScore = myScore; //create a reference


cout << "myScore is: " << myScore << "\n";

cout << "mikesScore is: " << mikesScore << "\n\n";

Using References 189


cout << "Adding 500 to myScore\n"; myScore += 500;

cout << "myScore is: " << myScore << "\n";

cout << "mikesScore is: " << mikesScore << "\n\n";


cout << "Adding 500 to mikesScore\n"; mikesScore += 500;

cout << "myScore is: " << myScore << "\n";

cout << "mikesScore is: " << mikesScore << "\n\n";


return 0;

}