section 2.4: Declarations

page 40

You may wonder why variables must be declared before use. There are two reasons:

  1. It makes things somewhat easier on the compiler; it knows right away what kind of storage to allocate and what code to emit to store and manipulate each variable; it doesn't have to try to intuit the programmer's intentions.
  2. It forces a bit of useful discipline on the programmer: you cannot introduce variables willy-nilly; you must think about them enough to pick appropriate types for them. (The compiler's error messages to you, telling you that you apparently forgot to declare a variable, are as often helpful as they are a nuisance: they're helpful when they tell you that you misspelled a variable, or forgot to think about exactly how you were going to use it.)

Although there are a few places where ``certain declarations can be made implicitly by context'', making use of these removes the advantages of reason 2 above, so I recommend always declaring everything explicitly.

Most of the time, I recommend writing one declaration per line (as in the ``latter form'' on page 40). For the most part, the compiler doesn't care what order declarations are in. You can order the declarations alphabetically, or in the order that they're used, or to put related declarations next to each other. Collecting all variables of the same type together on one line essentially orders declarations by type, which isn't a very useful order (it's only slightly more useful than random order).

If you'd rather not remember the rules for default initialization (namely that ``external or static variables are initialized to zero by default'' and ``automatic variables for which there is no initializer have... garbage values''), you can get in the habit of initializing everything. It never hurts to explicitly initialize something when it would have been implicitly initialized anyway, but forgetting to initialize something that needs it can be the source of frustrating bugs.

Don't worry about the distinction between ``external or static variables''; we haven't seen it yet.

One mild surprise is that const variables are not ``constant expressions'' as defined on page 38. You can't say something like

	const int maxline = 1000;
	char line[maxline+1];		/* WRONG */


Read sequentially: prev next up top

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