Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Global variables and style

Node:Global variables and style, Next:, 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.

 
 
  Published under free license. Design by Interspire