section 4.6: Static Variables

page 83

Deep sentence:

The static declaration, applied to an external variable or function, limits the scope of that object to the rest of the source file being compiled. External static thus provides a way to hide names like buf and bufp in the getch-ungetch combination, which must be external so they can be shared, yet which should not be visible to users of getch and ungetch.
So we can have three kinds of declarations: local to one function, restricted to one source file, or global across potentially many source files. We can imagine other possibilities, but these three cover most needs.

Notice that the static keyword does two completely different things. Applied to a local variable (one inside of a function), it modifies the lifetime (``duration'') of the variable so that it persists for as long as the program does, and does not disappear between invocations of the function. Applied to a variable outside of a function (or to a function) static limits the scope to the current file.

To summarize the scope of external and static functions and variables: when a function or global variable is defined without static, its scope is potentially the entire program, although any file which wishes to use it will generally need an extern declaration. A definition with static limits the scope by prohibiting other files from accessing a variable or function; even if they try to use an extern declaration, they'll get errors about ``undefined externals.''

The rules for declaring and defining functions and global variables, and using the extern and static keywords, are admittedly complicated and somewhat confusing. You don't need to memorize all of the rules right away: just use simple declarations and definitions at first, and as you find yourself needing some of the more complicated possibilities such as static variables, the rules will begin to make more sense.


Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995, 1996 // mail feedback