Sams Teach Yourself C in 21 Days

(singke) #1
Understanding Variable Scope 291

12


Creating Local Variables ....................................................................................


Alocal variableis one that is defined within a function. The scope of a local
variable is limited to the function in which it is defined. Day 5 describes local
variables within functions, how to define them, and what their advantages are. Local
variables aren’t automatically initialized to 0 by the compiler. If you don’t initialize a
local variable when it’s defined, it has an undefined or garbagevalue. You must
explicitly assign a value to local variables before they’re used for the first time.
A variable can be local to the main()function as well. This is the case for xin Listing
12.2. It is defined within main(), and as compiling and executing that program illus-
trates, it’s also only visible within main().

DOuse local variables for items such as
loop counters.
DOuse local variables to isolate the val-
ues the variables contain from the rest of
the program.

DON’Tuse external variables if they
aren’t needed by a majority of the pro-
gram’s functions.

DO DON’T


Static Versus Automatic Variables ................................................................

Local variables are automaticby default. This means that local variables are created
anew each time the function is called, and they are destroyed when execution leaves the
function. What this means, in practical terms, is that an automatic variable doesn’t retain
its value between calls to the function in which it is defined.
Suppose your program has a function that uses a local variable x. Also suppose that the
first time it is called, the function assigns the value 100 tox. Execution returns to the
calling program, and the function is called again later. Does the variable xstill hold the
value 100? No, it does not. The first instance of variable xwas destroyed when execution
left the function after the first call. When the function was called again, a new instance of
xwas created. The old xis gone.
What if the function needs to retain the value of a local variable between calls? For
example, a printing function might need to remember the number of lines already sent to
the printer to determine when it is necessary to start a new page. In order for a local vari-
able to retain its value between calls, it must be defined as staticwith the statickey-
word. For example:

NEWTERM

19 448201x-CH12 8/13/02 11:17 AM Page 291

Free download pdf