Globals, When and Why?

  • (2 Pages)
  • +
  • 1
  • 2

24 Replies - 3459 Views - Last Post: 16 May 2009 - 11:37 AM

#1 stayscrisp  Icon User is offline

  • フカユ
  • member icon

Reputation: 998
  • View blog
  • Posts: 4,173
  • Joined: 14-February 08

Globals, When and Why?

Post icon  Posted 04 May 2009 - 05:09 PM

When looking around the internet for tutorials and C++ discussions one thing runs through all of them, Global Variables are bad.

Yet when looking for a reason why there aren't many resources, I thought some people who have been severely burned by them could provide some insight?

I have always been taught as I'm sure others have that they are bad news and avoiding them is the best option yet without learning from experience its hard to see exactly why.

My reasons are:
  • Its hard to remember what all these variables do.
  • No Access Control or Constraint Checking

This post has been edited by skyhawk133: 04 May 2009 - 08:54 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Globals, When and Why?

#2 eker676  Icon User is offline

  • Software Engineer
  • member icon

Reputation: 378
  • View blog
  • Posts: 1,833
  • Joined: 18-April 09

Re: Globals, When and Why?

Posted 04 May 2009 - 05:50 PM

Sometimes I see the need for a global variable but usually most tasks can be accomplished without them.

I am with the whole encapsulation/data-hiding view. Why have 50 global variables when you could have one temp variable passed in by reference?

Global variables clutter the code IMO. All of the sudden a new variable will pop up. Then you have to scroll to the top and see what it does.
Was This Post Helpful? 0
  • +
  • -

#3 BlakeJustBlake  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 26
  • View blog
  • Posts: 441
  • Joined: 15-February 09

Re: Globals, When and Why?

Posted 04 May 2009 - 06:38 PM

Yeah, a big reason seems to be that you'll have something floating around that you'll have to go up and check. Then it clutters up the namespace, you can't really use that variable name anymore, I guess not a huge problem. Then, unless it's really necessary, it uses up more memory than it could be using.

Wikipedia has this to say about it:

Quote

They are usually considered bad practice precisely because of their nonlocality: a global variable can potentially be modified from anywhere, (unless they reside in protected memory) and any part of the program may depend on it. A global variable therefore has an unlimited potential for creating mutual dependencies, and adding mutual dependencies increases complexity. See Action at a distance. However, in a few cases, global variables can be suitable for use. For example, they can be used to avoid having to pass frequently-used variables continuously throughout several functions.

The use of global variables is particularly bad for functional programming languages (such as Scheme). It violates referential transparency and makes it very difficult to analyze code.

This post has been edited by BlakeJustBlake: 04 May 2009 - 06:39 PM

Was This Post Helpful? 0
  • +
  • -

#4 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3093
  • View blog
  • Posts: 19,139
  • Joined: 14-September 07

Re: Globals, When and Why?

Posted 04 May 2009 - 07:12 PM

I'll use a global pointer (and only one) if the program is small and I'm the only one writing it. Other then that--bad!
Was This Post Helpful? 0
  • +
  • -

#5 stayscrisp  Icon User is offline

  • フカユ
  • member icon

Reputation: 998
  • View blog
  • Posts: 4,173
  • Joined: 14-February 08

Re: Globals, When and Why?

Posted 05 May 2009 - 08:10 AM

Really bad reasons to use Globals
  • "What's a 'local variable'?"
  • "What's a 'data member'?"
  • "I'm a slow typist. Globals save me keystrokes."
  • "I don't want to pass it around all the time."
  • "I'm not sure in what class this data belongs, so I'll make it global."

@KYA I think that is definitely one of the accepted ways of using them, if your source code doesn't really exceed one file then they can be quick and useful. Aren't there some languages that have almost no support for non-global variables?


I have seen many a tutorial online with a load of globals each one with a big commented section dedicated to them, for one thing it looks ugly and also these sites claim to use OOP principles yet barrage you with globals and bad programming practice. :v:
Was This Post Helpful? 0
  • +
  • -

#6 polymath  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 52
  • View blog
  • Posts: 670
  • Joined: 04-April 08

Re: Globals, When and Why?

Posted 05 May 2009 - 02:19 PM

I use globals when they are needed. Mainly, i use them in the early planning stages of a program- normally i map out the functions and what they do and then i worry about making it "pretty". I agree, they are bad practice. However, there are a few times i find them particularly useful:

Two functions need to concurrently access the same resource, so you make a global pointer to the resource and simply *trust* (bad) anyone modifying your code not to write to the variable once it is initialized (ie = new *). My example is the IDT of a kernel (sorry i don't have a better example). The IDT (interrupt descriptor table) is a huge machine-readable table of which interrupts trigger which handlers. Since there is only ONE IDT in use, and several functions/subroutines, it can get tricky to pass it around by const& (especially because you're often dealing with assembly). Another example is the address of the current virtual console, because this isn't stored in a register (and as such isn't called as an argument to an interrupt). Sorry if this example doesn't relate to anyone. I'll come up with a better one later.

The good old small program excuse. IN small projects that are not intended to be expanded upon or modified (IE one file, <500LOC), it is useful to have a global value. My example for this is my science fair project. I wrote a ~450 line program to compare two WAV files. Since all the program would EVER be expected to do would be to compare two files, I made the files global since several functions would have to manipulate them.

Slightly related to the first (event handling, etc.) is multithreaded programming. It's difficult to pass variables to another thread, as you get shallow vs deep copy/reference problems and its difficult to implement a mutex to protect these variables if they're passed to multiple threads. Without the judicious use of global variables, your code can quickly look VERY messy.

I'm not an advocate of stuffing all of your global variables in a struct and having a global pointer to the struct. Face it- it's still globally accessible data, and should be treated as such. If you instantiate a variable in main and you make a global pointer to it- guess what?- you've just 'globalized' that variable. Since it's now globally accessible, that variable local to main is in effect actually global. ANd it's "messier" to mess with the pointer than having a global variable :)

Alright. That's my 2 cents. My only regret is it took so long. THe wikipedia article basically sums up what i have said much more eloquently :D
Was This Post Helpful? 0
  • +
  • -

#7 Hyper_Eye  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 39
  • View blog
  • Posts: 116
  • Joined: 13-September 07

Re: Globals, When and Why?

Posted 06 May 2009 - 01:34 PM

View Postpolymath, on 5 May, 2009 - 03:19 PM, said:

Slightly related to the first (event handling, etc.) is multithreaded programming. It's difficult to pass variables to another thread, as you get shallow vs deep copy/reference problems and its difficult to implement a mutex to protect these variables if they're passed to multiple threads. Without the judicious use of global variables, your code can quickly look VERY messy.


When doing multi-threaded programming I generally pass all the data needed by the threads to the threads in a structure. I then use common functions to work with the data because it makes mutex handling easy. I agree with some of what your saying but I don't think it is difficult at all to develop multi-threaded applications without using global variables. I do it all the time. I would actually say multi-threaded programs are a perfect example of when global variables can create the biggest problems!
Was This Post Helpful? 0
  • +
  • -

#8 polymath  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 52
  • View blog
  • Posts: 670
  • Joined: 04-April 08

Re: Globals, When and Why?

Posted 06 May 2009 - 03:31 PM

Quote

I would actually say multi-threaded programs are a perfect example of when global variables can create the biggest problems!


I agree, global variables can cause mayhem if several threads are accessing the same resource. However, globals allow for some additional simplicity. It's really all a compromise. If global variables are used correctly they can greatly decrease the amount of work in designing an API. Especially in C, where there is no OOP (struct evangelists- you can claim pseudo-oop, but that's not what i mean), you can run into multiple functions which need to access the same data. Lots of this data means having 6 or more arguments in a function (not pretty, we can all agree). Global variables, as long as used correctly, can be a powerful tool to simplify a project. Lots of people are saying pointers are bad practice now too. But we as C++ programmers know that these complex (by nature) packets of data can actually lend simplicity to a program (Imagine trying to do a dynamic-length array of runtime-constructed polymorphic classes without pointers- ugh). As I said before, programming style is really just accepting certain compromises. A few off of the top of my head:
1. Resource usage optimization vs. Speed optimization
2. Simplicity vs. Completeness (Complexity)
3. Readability vs. Workability

I'll stop rambling now, i realize i've gotten off topic.
Was This Post Helpful? 0
  • +
  • -

#9 no2pencil  Icon User is online

  • Toubabo Koomi
  • member icon

Reputation: 5191
  • View blog
  • Posts: 26,897
  • Joined: 10-May 07

Re: Globals, When and Why?

Posted 06 May 2009 - 08:55 PM

A long long time ago, one of the most difficult tasks to developing software was memory usage. Companies could spend thousands of dollars to shave kilobytes of memory usage off their binary executable, thus offering the customer a better product. I believe that most common (without though) negative aspects towards global variables is in relation to this time & place. With the computing power of today's machines, what's the overhead on an executable if you use 10 global variables? Extremely insignificant.

Just my 2
Was This Post Helpful? 0
  • +
  • -

#10 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Globals, When and Why?

Posted 06 May 2009 - 09:13 PM

The problem with global variables is just that we are all human. Global variables are a common source of stupid bugs which are often very hard to find. Like so many of ye-olde-pieces-of-wisdom such as not using goto -- it is not that you can't do it effectively it is that it is very easy for even a very good programmer to muck it up.

Global variables allow you to have code that looks and smells perfectly ok, and you stare and stress over it forever and can't figure out why in the hell it is not working.

So you load it up in the debugger and go to town, but rather than going line for line all the way though the code you use the debugger's "skip over" feature and still can't figure why the logic does not work... it SHOULD work... but unnoticed by you another function (also working perfectly logically) is changing your value.

Like I said, it is not that you CAN'T do it effectively -- sure you can, but even great programmers muck it up.
Was This Post Helpful? 0
  • +
  • -

#11 ApocalypzOrigin  Icon User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 573
  • Joined: 15-May 08

Re: Globals, When and Why?

Posted 07 May 2009 - 12:42 AM

Pretty much sums it up as best as possible. In some cases -for VERY small things- global variables can bring a welcome simplicity, but otherwise not using them just feels more secure to me. Like people have already said, its easy to mess up. If its global its open to everything, easier to use in everything. That could make it tempting to use in a few more places that you normally would. That makes it harder to keep track of. It may take more work to keep passing everything around, but it sets more rules on what can and can't be done with each piece of data. A bit restricting, but that keeps everything in check, helps hold it all together in a bigger project. Besides keeping the code in order, I've always found it easier to keep track of everything myself when each variable stays within it's own set scope.

This post has been edited by ApocalypzOrigin: 07 May 2009 - 12:42 AM

Was This Post Helpful? 0
  • +
  • -

#12 WolfCoder  Icon User is offline

  • Isn't a volcano just an angry hill?
  • member icon


Reputation: 782
  • View blog
  • Posts: 7,610
  • Joined: 05-May 05

Re: Globals, When and Why?

Posted 07 May 2009 - 12:54 PM

I use globals for very important things such as time_step and game_width game_height. I need some globally valid variables that define the time and space.

However, if you're using a strongly object oriented language like C++, you can simply make static constants that can be read publicly. Same goes for JAVA. Then it would be

GameEngine.timeStep;



Except in the case of timeStep, it's an ever-changing variable and not constant.

You'll always have namespace issues, so thats why I prefix all my extern functions.

This post has been edited by WolfCoder: 07 May 2009 - 12:55 PM

Was This Post Helpful? 0
  • +
  • -

#13 mikeblas  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 43
  • View blog
  • Posts: 390
  • Joined: 08-February 08

Re: Globals, When and Why?

Posted 09 May 2009 - 08:42 PM

I've never understood why they're bad, either.

This thread seems like it's full of a lot of religion and really light on reasoning, insight, and explanation.

I've never read any research that says global variables cause more bugs than local variables. In fact, I've never read anything which breaks down bugs to what scope of variable caused them. Most of the bugs I've seen were caused by programmer error, or a misunderstanding about requirements, or a bad assumption about a contract over an interface.

It's hard to remember what variables do whether they're global, local, automatic, or class members. I can't understand how globals would be any different in this regard.

Globals aren't exclusive to encapsulation: a class instance can be global, and therefore can encapsulate the access to the data the class owns or wraps.

I can't figure out how globals might cause code clutter any more than any other declaration does. I think cluttered code is more likely to come from code which artificially inflates, accessor-izes, and wraps something that should have just been a plain old variable.

Depending on the language (and, I guess, your understanding of the language) you can use the name of a global again any time you want to. A global named "foo" is discernible from a local named "foo" in C++, for example, because the compiler considers the local scope automatically first. If you don't want it to, you can scope the global as "::foo". What's the big deal?

You know that anyone can edit Wikipedia, by the way, right?

Globals actually make multithreaded programming possible. If there weren't globals, there would be no way to lock objects at the higher scope.

I wonder; why do people worry about global variables, and not global functions? Don't they have almost all the same problems that global variables do?

A problem that several people here mentioned was that the variable can be changed by any function. This is true for any variable, right? If you call some other function, everything is free game. Depending on your programing environment, maybe even locals are alterable by other functions.

If you really know what "static" means and use it, aren't true globals incredibly rare?

Altruisms about programming are pretty bad. I can't imagine doing any embedded programming without globals. While embedded products are the most common applications in the world, people are being taught that globals are bad. How can this be?
Was This Post Helpful? 0
  • +
  • -

#14 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Globals, When and Why?

Posted 09 May 2009 - 09:38 PM

Quote

Most of the bugs I've seen were caused by programmer error, or a misunderstanding about requirements, or a bad assumption about a contract over an interface.
Bugs caused by global variables ARE programmer error, and that is often caused by misunderstanding design or misunderstanding of real world use cases.

There is nothing directly wrong with global variables. The problem is ensuring their safety. They are inherently unsafe.

Global variables create inter process dependencies. Care has to be taken to ensure that while one routine is using the variable another routine does not modify the value for its own use.

Take as a poor example the width of a window... one function reads the width in preparation for drawing a graphic, but before it does the actual drawing it calls an initialization routine that resizes the window -- now the value has changed and the initial routine misdraws the graphic. Now if 99.9% of the time the window is already the correct size then the conflict may never come up in testing and not be discovered until some user adjusts the size of the window. -- poor example I know, we all KNOW not to do it this way, if the drawing procedure has a dependency upon the initialization routine then before the drawing routine does anything it should call the initialization routine... but with global variables you will always have these dependencies.

If you are not careful you can create mutual dependencies and without concurrent practices like mutex's and locks these mutual dependencies almost always result in bugs (which like the resizing example only turn up in untested usecases -- if they were tested the programmer would realize his/her mistake and work around it).


Think about it this way, Concurrent programming can be very challenging because of race conditions -- global variables always suffer from race condition -- you have to ensure that the variables are accessed in the correct order and the more dynamic your program the more difficult this is.

Add a development team larger than 1 and this really becomes a problem.

Global functions are not a problem because they are only read. Global constants are ok -- no one cares if you use a global constant -- well actually I can think of 1 reason not to:

Another reason to act locally and not globally is discussed in the Herb Stutter talk I posted: Global variables will cause cache misses -- cache misses drastically slow down a program.

Like the T-shirt says: Think globally, act in local variable scope.
Was This Post Helpful? 0
  • +
  • -

#15 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3093
  • View blog
  • Posts: 19,139
  • Joined: 14-September 07

Re: Globals, When and Why?

Posted 09 May 2009 - 10:02 PM

Maximize cohesion, minimize coupling. Ba da bing, ba da boom
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2