The variable g2 is global because it’s defined before a function (prAgain()).
Local variables are usable only within their own block of code. Therefore, l1 could never be printed
or changed in prAgain() because l1 is local to main(). Conversely, l2 could never be used in
main() because l2 is visible only to prAgain(). The variable g1 is visible to the entire
program. g2 is visible only from its point of definition down.
Tip
All global variables are known from their points of definition down in the source file.
Don’t define a global variable in the middle of a program (as is done in the preceding
program) because its definition can be too hard to find during debugging sessions. You
should limit (or eliminate) the use of globals. If you use them at all, define all of them
before main(), where they are easy to find (such as if you need to change them or
look at their defined data types).
The program outline shown earlier has a problem. If you use only local variables (and you should
always try to), the user ID created in assignID() cannot be used in buildContact() or
addPayroll(). Stay tuned—the next chapter shows you the solution.
Warning
If you compile the previous program and receive a compiler warning about a call to a
function without a prototype, ignore the warning for now. Chapter 32, “Returning Data
from Your Functions,” answers your questions.
The Absolute Minimum
The goal of this chapter was to teach you the building-block approach to writing C
programs. Long programs can become unwieldy unless you break them into several
separate functions. One long main() function is analogous to a long book without
chapter divisions. Break your long programs into separate functions, and have each
function perform a single, separate task in the program.
When you divide your programs into several functions, you have to consider how
variables are used throughout the code. Local variables are defined inside a function
and are usable only in that function. The opposite of a local variable is a global
variable, whose value is usable in all functions after its definition. Global variables
are frowned upon. Local variables are safer because you can limit their access to only
functions that need to use them. In the next chapter, you learn how to share local
variables between functions. Key concepts from this chapter include:
- Define local variables after a block’s opening brace. Define global variables before