section 4.4: Scope Rules

page 80

With respect to the ``practical matter'' of splitting the calculator program up into multiple source files, though it's certainly small enough to fit comfortably into a single source file, it's not so small that there's anything wrong with splitting it up into multiple source files, especially if we start adding functionality to it.

The scope of a name is what we have been calling its ``visibility.'' When we say things like ``calling a function with a prototype in scope'' we mean that a prototype is visible, that a declaration is in effect.

The variables sp and val can be used by the push and pop routines because they're defined in the same file (and the definitions appear before push and pop). They can't be used in main because no declaration for them appears in main.c (nor in calc.h, which main.c #includes). If main attempted to refer to sp or val, they'd be flagged as undefined. (Don't worry about the visibility of ``push and pop themselves.'')

The paragraph beginning ``On the other hand'' is explaining how global (``external'') variables like sp and val could be accessed in a file other than the file where they are defined. In the examples we've been looking at, as we've said, sp and val can be used in push and pop because the variables are defined above the functions. If the variables were defined elsewhere (i.e. in some other file), we'd need a declaration above--and that's exactly what extern is for. (See page 81 for an example.)

page 81

A definition creates a variable, and for any given global variable, you only want to do that once. Anywhere else, you want to refer to an existing variable, created elsewhere, without creating a new, conflicting one. Referring to an existing variable or function is exactly what a declaration is for.

Note also that the definition may optionally initialize the variable. (Don't worry about why a declaration may optionally include an array dimension.)

``This same organization would also be needed if the definitions of sp and val followed their use in one file'' means that we could conceivably have, in one file,

		extern int sp;
		extern double val[];


void push(double f) { ... } double pop(void) { ... }

int sp = 0; double val[MAXVAL];
So ``extern'' just means ``somewhere else''; it doesn't have to mean ``in a different file,'' though usually it does.


Read sequentially: prev next up top

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