18 Intermediate C Programming
2.3.3 Local Variables
If a function has local variables, then the local variables are stored in the call stack.
Consider the following program:
void f1 ( i n t k , in t m , int p)1
{2
int t = k + m;3
int u = m * p;4
}5
6
void f2 ( void)7
{8
f2 (5 , 11 , -8) ;9
// RL A10
}11
The arguments k, m, and p are stored above the return location A. The local variables
t and u are stored on the call stack above the arguments.
Frame Symbol Address Value
f1
u 105 -88
t 104 16
p 103 -8
m 102 11
k 101 5
Return Location 100 line 12
Now one more call stack rule must be added.
• If a function has local variables, then the local variables are stored above the argu-
ments.
• If a function has arguments, then the arguments are stored above the return location.
• The arguments and the return location together form the frame of the called function.
• When a function is called, the line number after this call is pushed onto the call stack.
This line number is the “return location” (RL). This is the place from which the
program will continue after the called function finishes (i.e., returns).
• If the same function is called from multiple lines, then each call has a corresponding
return location (the line after each function call).
• When a function finishes, the program continues from the line number stored at the
top of the call stack. The top of the call stack is then popped.
Local variables are always stored on the stack, where they reside for the duration of the
function call. They exist in contrast to “global variables”, which persist between function
calls. Global variables are usually specified at the top of a given source file, and any function
can read and write to them. While sometimes convenient, global variables can lead to subtle
software bugs. In 1973, Wulf et al. wrote an article, “Global Variables Considered Harmful”.
It explained in some detail why programmers should avoid global variables. The software
community generally concurs, and use of global variables has been strongly discouraged
since then. Although C allows global variables, well-written software almost always avoids
global variables. The main problem is that global variables may be changed anywhere in a
program. As the program becomes larger and more complex, it becomes increasingly harder
to track the places where these global variables may change. Losing track of the changes
can often lead to surprising behavior in the program. For further information, please read
Wulf’s paper to understand why global variables are problematic. Although global variables