Visibility

Every variable in a C program has a definite “visibility” that determines which parts of the program can “see,” or access, the variable. Another term for visibility is “scope.”

As we mentioned in Chapter 1, “Anatomy of a C Program,” there are two basic kinds of visibility: local and external. A “local” variable—one declared within a function—is visible only within that function. An “external” variable—one declared outside all functions—is visible to all functions that follow it in the program.

This section begins by describing local and external visibility, then goes on to discuss visibility in multiple-file programs and the visibility of functions.

NOTE:

While the examples in this section use simple int variables, visibility rules apply equally to aggregate types such as arrays and structures.

Summary: Use external variables only when necessary.

C programmers normally limit the visibility of each variable to those parts of the program that need to access the variable. For instance, if a variable is needed only within one function, it should always be local to that function. By restricting a variable's visibility, you can prevent other parts of the program from accidentally changing the variable's value. Such haphazard side effects were common in older interpreted Basic programs, in which every variable had unlimited visibility.