img wangjiong

General Issuess in Using Variables

发表于2004/9/29 22:29:00  657人阅读

Data Declaration
Implicit declaration is one of the most hazardous features available in any language.

Initializing Variables
Improper data initialization is one of the most fertile sources of error in computer programming.
1. Initialize each variable as it's declared.
2. Initialize each variable close to where it's first used.
If the language doesn't support initializing variables as they'are declared, then use the 2.
3. Ideally, declare and define each variable close to where it's used.
4. Pay special attention to counters and accumulators.
A common error is forgetting to reset a counter or an accumulator before the next time it's used.
5. Initialize a class's memeber data in its constructor.
6. check the need for reinitialization.
7. Inititalize named constants once; initialize variables with executable code.
8. Use the compiler setting that automatically initializes all variables.
9. Check input parameters for validity.
Before you assign input values to anything, make sure the values are reasonalbe.

Scope of variable
Keep variables live for as short a time as possible.
1. Initialize variables used in a loop immediately before the loop rather than back at the beginning of the routine containing the loop.
2. Don't assign a value to a variable until just before the value is used.
3. Group related statements.
Example in P14
4. Begin with most restricated visibility, and expand the variable's scope only if necessary.

Using each variable for exactly one purpose.
Avoid variables with hidden meanings, such as the error number as -1
Make sure that all declared variables are used.


0 0


取 消