Stacks are a data structures which are already very familiar with. What we are going to look at is a very important use of a stack. This is sometimes also called the procedure stack, however as most programmers are very familiar with the procedure stack we tend to just refer to it as the stack.

The stack is simply a block of memory. The memory is managed by the computer language in the form of a stack. It is important to remember that the programmer does not directly manipulate the stack but they must be very aware of it as we will see later.

In order to understand how the stack is used we need a simple code example

X()

Function x()

Dim A

A = 3.14

Y(A)

End

Function y(D)

Dim C

C = 2 * 6 * D

Z(c)

End

 

Function z(P)

Print P

End

 

Initially the stack will be empty. When a procedure is called, such as X(), we add the procedure to the stack. This is shown below.

 

X() :- A = 3.14

 

When we call Y(A) we again must add that procedure call to the stack as can be seen below. As this is a stack, the call to the procedure is placed on top of the last one. This way the currently running procedure is always the one on top. Every time a new procedure is called, it is placed on top.

Y() :- D = 3.14, C = 37.68

X() :- A = 3.14

The next function to call is z() , as shown below. As z() does very little other than to print out a number it will obviously end quickly. When z() ends the language must pop the stack. It will then return to the point it was called. As such every time we call a new procedure we must also keep a track of exactly where the code was in order to jump back. This is stored in the stack as well. As we go back through the stack, each procedure gets popped until the program finishes.

Z() :- p = 37.68

Y() :- D = 3.14, C = 37.68

X() :- A = 3.14

When you debug a program or an expectation happens from within your code you should have opportunity to see the stack trace. A stack trace simply is the displaying of the stack. It normally will not display variables but it will display line numbers. This was if there is a problem with the code you can trace it back quickly and also see what actually called the offending code. The image below shows part of a stack trace.