Sams Teach Yourself C in 21 Days

(singke) #1
The only difference between Listings 12.1 and 12.2 is where variable xis defined. By
moving the definition of x, you change its scope. In Listing 12.1,xis defined outside of
main()and is therefore an external variable,and its scope is the entire program. It is
accessible within both the main()function and the print_value()function. In Listing
12.2,xis defined inside a function, the main()function, and is therefore a local variable
with its scope limited to within the main()function. As far as print_value()is con-
cerned,xdoesn’t exist, and this is why the compiler generated an error message. Later in
today’s lesson, you’ll learn more about local and external variables, but first you need to
understand the importance of scope.

Why Is Scope Important? ..............................................................................

To understand the importance of variable scope, you need to recall the discussion of
structured programming on Day 5. The structured approach, you may remember, divides
the program into independent functions that each perform a specific task. The key word
here is independent. For true independence, it’s necessary for each function’s variables to
be isolated from possible interference caused by code in other functions. Only by isolat-
ing each function’s data can you make sure that the function goes about its job without
some other part of the program throwing a monkey wrench into the works. By defining
variables within functions, as you will learn soon, you can “hide” those variables from
other parts of the program.
If you’re thinking that complete data isolation between functions isn’t always desirable,
you are correct. You will soon realize that by specifying the scope of variables, a pro-
grammer has a great deal of control over the degree of data isolation.

Creating External Variables ................................................................................


Anexternal variableis a variable defined outside of any function. This means
outside of main()as well because main()is a function, too. Until now, most of
the variable definitions in this book have been external, placed in the source code before
the start of main(). External variables are sometimes referred to as global variables.

288 Day 12

If you don’t explicitly initialize an external variable (assign a value to it)
Note when it’s defined, the compiler initializes it to 0.

NEWTERM

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

Free download pdf