Every variable that you have seen so far in the example programs has been an
auto (think of that as automatic) variable. An auto variable can be declared
at the beginning of any block of code that is enclosed in ``curly braces,''
whether that block is the body of a function, of a while loop, or anything
else. Most often, though, auto variables are declared at the beginning of a
function body.
Since you are so used to auto variables, this is a good place to start
our discussion of storage classes. Take a look at the program
``auto.c'' in your ``examples'' directory (or view it
directly). What is new about the way
variables are declared in this program?
Click here for the answer
The keyword ``auto'' is a storage modifier, and tells C that the variable
should be treated as an auto variable. It is important to note, however, that
this particular storage modifier is completely redundant. By default,
variables declared within functions are assumed by C to be auto variables. So
you will most likely never see the ``auto'' keyword in a real C program.
Since it turns out that you already know all about ``auto'' variables, you
should be able to answer the following four questions:
- When is an automatic variable allocated in memory?
Click here for the answer
- When is an automatic variable initialized?
Click here for the answer
- Where is an automatic variable visible?
Click here for the answer
- When is an automatic variable deallocated from memory?
Click here for the answer
When we look at the ``static'' and ``extern'' storage classes, you'll see how
the answers to some of the questions change.
Now compile and run ``auto.c''. You'll no doubt notice that it prints out the
same ``random'' number ten times in a row. Given what you know about automatic
variables, what is wrong with our program?
Click here for the answer
In the next section, we'll see a way to fix this problem.
Hamlet Project
hamlet@cs.utah.edu