Sams Teach Yourself C in 21 Days

(singke) #1
Understanding Variable Scope 299

12


Summary ............................................................................................................


Today’s lesson covered the concept of scope and lifetime as related to C’s variable stor-
age classes. Every C variable, whether a simple variable, an array, a structure, or what-
ever, has a specific storage class that determines two things: its scope, or where in the
program it’s visible; and its lifetime, or how long the variable persists in memory.
Proper use of storage classes is an important aspect of structured programming. By keep-
ing most variables local to the function that uses them, you enhance functions’ indepen-
dence from each other. A variable should be given automatic storage class unless there is
a specific reason to make it external or static.

Q&A ....................................................................................................................


Q If global variables can be used anywhere in the program, why not make all
variables global?
AAs your programs get bigger they will contain more and more variables. Global
variables take up memory as long as the program is running, whereas automatic
local variables take up memory only while the function they are defined in is exe-
cuting. Hence, use of local variables reduces memory usage. More important, how-
ever, is that the use of local variables greatly decreases the chance of unwanted
interactions between different parts of the program, hence lessening program bugs
and following the principles of structured programming.
Q Day 11, “Implementing Structures, Unions, and TypeDefs” stated that scope
affects a structure instance but not a structure tag or body. Why doesn’t scope
affect the structure tag or body?
AWhen you declare a structure without instances, you are creating a template, or
definition, but not actually declaring any variables. It isn’t until you create an
instance of the structure that you declare a variable that occupies memory and has

DOuse variables at the beginning of a
block (temporarily) to help track down
problems.

DON’Ttry to put variable definitions
anywhere other than at the beginning of
a function or at the beginning of a
block.
DON’Tdefine variables at the beginning
of a block unless it makes the program
clearer.

DO DON’T


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

Free download pdf