2.5 Memory Concepts

Variable names such as number1, number2 and sum actually correspond to locations in the computer’s memory. Every variable has a name, a type, a size and a value.

In the addition program of Fig. 2.5, when the statement in line 13


std::cin >> number1; // read first integer from user into number1

is executed, the integer typed by the user is placed into a memory location to which the name number1 has been assigned by the compiler. Suppose the user enters 45 for number1. The computer will place 45 into the location number1, as shown in Fig. 2.6. When a value is placed in a memory location, the value overwrites the previous value in that location; thus, placing a new value into a memory location is said to be a destructive operation.

Fig. 2.6 Memory location showing the name and value of variable number1.

Returning to our addition program, suppose the user enters 72 when the statement


std::cin >> number2; // read second integer from user into number2

is executed. This value is placed into the location number2, and memory appears as in Fig. 2.7. The variables’ locations are not necessarily adjacent in memory.

Fig. 2.7 Memory locations after storing values in the variables for number1 and number2.

Once the program has obtained values for number1 and number2, it adds these values and places the total into the variable sum. The statement


sum = number1 + number2; // add the numbers; store result in sum

replaces whatever value was stored in sum. The calculated sum of number1 and number2 is placed into variable sum without regard to what value may already be in sum—that value is lost. After sum is calculated, memory appears as in Fig. 2.8. The values of number1 and number2 appear exactly as they did before the calculation. These values were used, but not destroyed, as the computer performed the calculation. Thus, when a value is read out of a memory location, the operation is nondestructive.

Fig. 2.8 Memory locations after calculating and storing the sum of number1 and number2.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset