- 2.1 Introduction
- 2.2 First Program in C++: Printing a Line of Text
- 2.3 Modifying Our First C++ Program
- 2.4 Another C++ Program: Adding Integers
- 2.5 Memory Concepts
- 2.6 Arithmetic
- 2.7 Decision Making: Equality and Relational Operators
- 2.8 Wrap-Up
- Self-Review Exercises
- Answers to Self-Review Exercises
- Making a Difference
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
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 Memory location showing the name and value of variable number1.
Returning to our addition program, suppose the user enters 72 when the statement
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 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
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 Memory locations after calculating and storing the sum of number1 and number2.