Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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 14

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 as the value 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 destructive.

Fig. 2.6

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

Fig. 2.7 Memory locations after storing values 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 process is nondestructive.

Fig. 2.8

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

  • + Share This
  • 🔖 Save To Your Account