Sams Teach Yourself C++ in 21 Days

(singke) #1
Organizing into Functions 131

5


When data is pushedonto the stack, the stack grows; as data is poppedoff the stack, the
stack shrinks. It isn’t possible to pop a dish off the stack without first popping off all the
dishes placed on after that dish.
A stack of dishes is the common analogy. It is fine as far as it goes, but it is wrong in a
fundamental way. A more accurate mental picture is of a series of cubbyholes aligned top
to bottom. The top of the stack is whatever cubby the stack pointer (which is another reg-
ister) happens to be pointing to.
Each of the cubbies has a sequential address, and one of those addresses is kept in the
stack pointer register. Everything below that magic address, known as the top of the
stack, is considered to be on the stack. Everything above the top of the stack is consid-
ered to be off the stack and invalid. Figure 5.8 illustrates this idea.

FIGURE5.7
A stack.


FIGURE5.8
The stack pointer.


Stack

80

100
101
102
103
104
105
106
107
108
109
110

YourAge 37

MyAge 50

on the stack

off the stack

stack pointer
theVariable^102
Free download pdf