|
|
|
|
|
|
|
Although an initialization gives a variable an initial value, it is perfectly acceptable to reassign it another value during program execution. |
|
|
|
|
|
|
|
|
The following table summarizes initialization of static and automatic variables. |
|
|
|
|
| Automatic variables | Static variables | | Initialized when? | Each time control reaches the declaration | Once only, the first time control reaches the declaration | | Initializer | Any expression* | Constant expression only* | | *Implicit type coercion takes place if the data type of the initializer is different from the data type of the variable. |
|
|
|
|
|
|
There are differing opinions about initializing a variable in its declaration. Some programmers never do it, preferring to keep an initialization close to the executable statements that depend on that variable. For example, |
|
|
|
|
|
|
|
|
int loopCount;
.
.
.
loopCount = 1;
while (loopCount <= 20)
{
.
.
.
} |
|
|
|
|
|
|
|
|
Other programmers maintain that one of the most frequent causes of program bugs is forgetting to initialize variables before using their contents; initializing each variable in its declaration eliminates these bugs. As with any controversial topic, most programmers seem to take a position somewhere between these two extremes. |
|
|
|
|
|
|
|
|
We return now to the issue of interface design, which we first discussed in Chapter 7. Recall that the data flow through a function interface can take three forms: incoming only, outgoing only, and incoming/outgoing. Any item that can be classified as purely incoming should be coded as a value parameter. Items in the remaining two categories (outgoing and incoming/ outgoing) must be reference parameters; the only way the function can |
|
|
|
|
|