Discussion
Team LiB
Previous Section Next Section

Discussion

Variables whose lifetimes are longer than necessary have several drawbacks:

  • They make the program harder to understand and maintain: For example, should code update the module-wide path string if it only changes the current drive?

  • They pollute their context with their name: As a direct consequence of this, namespace-level variables, which are the most visible of all, are also the worst (see Item 10).

  • They can't always be sensibly initialized: Never declare a variable before you can initialize it sensibly. Uninitialized variables are a pervasive source of bugs in all C and C++ programs, and they require our proactive attention because they can't always be detected by compilers (see Item 19).

In particular, older versions of C before [C99] required variables to be defined only at the beginning of a scope; this style is obsolete in C++. A serious problem with this restriction is that at the beginning of the scope you often don't yet have enough information to initialize variables with pertinent information. This leaves you with two choiceseither initialize with some default blank value (e.g., zero), which is usually wasteful and can lead to errors if the variable ends up being used before it has a useful state, or leave them uninitialized, which is dangerous. An uninitialized variable of user-defined types will self-initialize to some blank value.

The cure is simple: Define each variable as locally as you can, which is usually exactly the point where you also have enough data to initialize it and immediately before its first use.

    Team LiB
    Previous Section Next Section