18. Declare variables as locally as possible

Summary

Avoid scope bloat, as with requirements so too with variables: Variables introduce state, and you should have to deal with as little state as possible, with lifetimes as short as possible. This is a specific case of Item 10 that deserves its own treatment.

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 ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.