Monday, August 5, 2013

C++ using globals

The rule that you should almost never break: Never use globals.

Reasons:

 
1) Namespacing. Compilers are very good at telling you that a name is already taken. Once your application passes 10k lines of code, the number of namespace problems you will face increases exponentially. Global variables each need a unique name and the more you use, the harder it is to invent new ones.

 
2) Working with other people. As sure as there is a Sun, people on your project will misuse your global variables. Your global variable set to 0 will almost always mean something to one person and something else to someone else. Globals are notorious for causing fragility for this very reason.

 
3) Instancing and memory. A global variable is created before you ever hit main. Complex variable types will even invoke 'new' meaning that crashes can and do happen before you hit main. No debugger in the World will help you find that bug. You will never find it through debugging IOW. You'll have to be smarter than the compiler. Also, crashing on exit is another side-effect of globals. Most apps that have complex global variables are not able to clean up correctly and crash when exiting. These kinds of problems are ruthlessly difficult to solve.

 
4) Design. Relying on globals means that you are probably not a very good organizer. Code should be organized well and relying on globals means that you've run out of ideas and controlling how data is passed, initialized, stored. Look into better designs and your life becomes easier.

 
5) Performance. Globals are slower than local variables (stack) or member variables (usually part of the stack, but they are usually cached). Globals are stored in another part o the application that you have no control over, neither stack nor cache and this will rarely be cached and so will almost always be slower.

 
6) Address space. Globals are in a memory space that is in the same memory space as your application. If you have a string, for example, and you write past the end of your string (a common beginner mistake), you will actually overwrite the code itself. This can create some very interesting results.

 
7) Portability. Code that relies on globals, especially across modules, is not reusable... in general. I would even go as far as to say that you will never be able to use that code outside of that one project.

No comments: