C: Global Variables versus Parameters

Moderator
Posts: 3,552
Joined: 2003.06
Post: #2
Generally speaking, if you have a function that calls another and it's affecting a variable that's only used in that function, yes, don't use a global for that.

Yes, you should avoid using globals if you really don't need to. Knowing when to use one or not takes experience.

Ahem... That said, personally I find absolutely nothing wrong with using globals whenever I darn-well want to!

One thing you will want to do though is distinguish between globals that are available anywhere in the program, or globals that are only available within the scope of that source file. The reason you want to keep your globals within the scope of that file is because it's easy to forget that you used a variable name in one file and then tried to use it again for something else in another file. The way you keep the global local to that file is by simply prefixing the declaration with the keyword, static. Example:

static int gMyGlobal;

It's a great habit to get into so you can keep your code more modular and easy to deal with.

So, with all that said, do be aware that over-use of global variables is considered "bad form" by many. It's also a source of poor performance in some cases because the global has to be loaded, whereas if you can keep a variable local it can be stored in a register. Those performance details aren't really all that important to know as you're learning, but just something to keep in mind.

One tip I would highly recommend (even insist) is that when you create a global variable it is an absolute must that it be named in such a way as to make it clear what it is. If you can't do that, at least be sure to write a good comment next to it where you declare it to describe what it's for. Local variables often document themselves, just by what they're used for in a particular function, but globals, being global in scope, don't always have that context to help hint at what they're for.
Quote this message in a reply
Post Reply 


Messages In This Thread
C: Global Variables versus Parameters - AnotherJake - Jan 12, 2010 08:50 PM
C: Global Variables versus Parameters - DoG - Jan 13, 2010, 05:03 AM
Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Accessing an inherited class's variables Tobs_ 22 8,385 Feb 28, 2007 05:26 PM
Last Post: mac_girl
  Problems with variables in Obj-C vnvrymdreglage 16 5,934 Oct 2, 2006 10:19 PM
Last Post: vnvrymdreglage
  Should global variables be pointers or full objects? ia3n_g 1 2,066 Aug 4, 2006 05:53 PM
Last Post: OneSadCookie
  where do global variables fall into the memory type? WhatMeWorry 3 2,524 Jun 5, 2006 02:45 PM
Last Post: OneSadCookie
  Arrays or variables containing executable functions Jones 4 3,747 Jun 2, 2006 08:35 AM
Last Post: Zekaric