Node:Global variables and style, Next:Hidden operators and style, Previous:Declarations and initialization, Up:Style
Global variables and style
Global variables have caused almost as much controversy as the
goto
statement. Some programmers say you should never use
them. Other programmers use them on a regular basis. In fact, while
global variables should not be overused, they can simplify your code
considerably. The following guidelines may help you decide where to
use globals.
- Always think of using local variables first. Global variables can puncture the encapsulization of your functions, that is, the logical isolation of your functions from the rest of your code. It is difficult to see what variables are being passed to a function unless they are all passed as parameters, so it is easier to debug a program when encapsulization is maintained.
- Local variables may be impractical, however, if they mean passing the same dozen parameters to multiple functions; in such cases, global variables will often streamline your code.
- Data structures that are important to the whole program should be defined globally. In "real programs" such as GNU Emacs, there are far more global variables than there are local variables visible in any one function.
Finally, don't use local variables or parameters that have the same names as global identifiers. This can make debugging very difficult.