Globals usage in tutorials and elsewhere.

Started by
20 comments, last by Hodgman 10 years, 5 months ago

As someone that has published a programming book I can offer some insight.

First, the concept you are demonstrating trump "clean" code. You use the code that most clearly represents what you want to demonstrate, not necessarily the code that is the best. This is one of my big complaints about JavaScript: The Good Parts... it's an excellent book, but the author was trying to be overly cleaver with his example applications, which makes it a heck of a lot harder to figure out the basic concepts he is trying to demonstrate.

Second, writing code for the printed page is vastly different then writing code on a 1080p monitor! This has a huge impact on the types of samples you can create. When you have to keep code length in mind, namespaces for example, become the first victim.

Third, you often need to create a template that further examples build off of. Generally you want your source samples to be in a single code unit ( AKA, a .c, .java or .cs file ) or it gets much harder to understand and document. Thus you often develop some boilerplate code so you dont have to repeat it over and over. This often means making a number of global(ish) variables.

So, a number of factors go in to writing sample code in books that arent a factor for day to day programming. What you do not do however, is make global loop counters! smile.png

Advertisement

I tend to use both Globals and Local Variables. I use Globals for mundane task which may be used in several Functions through out the coding.

For Example : int x,y; // Loop Counters These I declare up front instead of declaring them in Each function I would use a Counter.

I Keep Conditional Variables Local For Example char Option; while(Option=='A') { Do This }

While there are many more examples for both, Such as your Graphical settings would be global, Arrays could be global . Basically any variable that you would see a need to use that information throughout the program should be Global

Don't do this. smile.png Let's say you managed to keep that straight throughout your development process. Consider what will happen if you decide to make your program multi-threaded. Your loops would start going bananas as they all fought over the shared resource of the global counters.

Or heck, even in a single thread, what will happen if you iterate over a hierarchy of objects. Let's say your GameObject class has a list of child GameObjects. If you used your global loop counter, you'd have to come up with your own stack management technique.

To Mercury Filter: Do a quick search on when will global variables bite you. The first little article that pops up looks decent.

http://c2.com/cgi/wiki?GlobalVariablesAreBad

There are some cases when a global variable might make sense, but there's almost always a better way. If you're having to jump through a ton of hoops to avoid using global variables, you might need to revisit your code and see if it's in need of a little refactoring.

And if you have to use global variables, don't name them something as simple as x or y because then you'll accidentally collide with others variables named that. It will cloud what your intention was and sometimes you might be accessing the global "x' when you meant to access the local "x".

Real World Case:

I worked with a profesional developer guy who was paid to do development. There was this dial in menu system that worked 99% of the time. But every once in a while it started acting weird as hell. The problem only happened in production, but we could never reproduce it in the developer's or QA's environment. Turns out the issue was a global variable and if two people dialed in at the same time, they'd start stepping on each other's toes, hearing each others menu options, and messing with each other's data.

- Eck

EckTech Games - Games and Unity Assets I'm working on
Still Flying - My GameDev journal
The Shilwulf Dynasty - Campaign notes for my Rogue Trader RPG

I tend to use both Globals and Local Variables. I use Globals for mundane task which may be used in several Functions through out the coding.

For Example : int x,y; // Loop Counters These I declare up front instead of declaring them in Each function I would use a Counter.

Oh the humanity

"Spending your life waiting for the messiah to come save the world is like waiting around for the straight piece to come in Tetris...even if it comes, by that time you've accumulated a mountain of shit so high that you're fucked no matter what you do. "


And if you have to use global variables, don't name them something as simple as x or y because then you'll accidentally collide with others variables named that. It will cloud what your intention was and sometimes you might be accessing the global "x' when you meant to access the local "x".

Well This is a Duh. Yes when using Global Variables you do your best not to use those same Variables as locals.

Let me state. That I Keep them in a simple use, nothing complicated. And I only use them in a controlled environment. and I think the way I originally stated their use is perfectly fine. If you disagree I am sure I will be hit for it , but if you agree.....Well fix it.

For(x=0; x<10;x++); < Controlled loop, Read Data, Check arrays

How many of you setup let us say your graphical view port with MAXWidth/MAXHieght ? Local or Global declaration ? How many time do you reuse these variables as Locals ?

Your Brain contains the Best Program Ever Written : Manage Your Data Wisely !!


So, a number of factors go in to writing sample code in books that arent a factor for day to day programming. What you do not do however, is make global loop counters!

I did not say I use Global Loop Counters, I said I use Global Variables as a Loop Counter. There is a difference. Apparently All of you brainiacs do not seem to think the others are capable of doing / and controlling something you can not.

I have been programming in various languages for 25+ years, albeit simple apllications not games, maybe there is a difference. But I never had a problem with my use of globals and the way I use them.

Look beyond your own experiences and realize that something can be done differently and effectively. Maybe I have an advantage, I code alone. so my usage of globals is well known be me.

Your Brain contains the Best Program Ever Written : Manage Your Data Wisely !!

Global variables as a loop counter is bad (can't do recursion, or multiple threads).

Global constants for loop ranges is ok (although probably better in a narrower scope e.g. static class or in a namespace to avoid name collisions). I think you may be confused about terminology?

EDIT: Global variables for loop ranges is also ok as long as you have no issues with different threads using out of date values.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

Look beyond your own experiences and realize that something can be done differently and effectively. Maybe I have an advantage, I code alone. so my usage of globals is well known be me.

Try not to take this personally, people here tend to be, hmmm... wordy... sometimes. It is just that he is probably a beginner and people want to make sure he understand the problems of such approach. I am pretty sure most of us who are warning about the problems with globals have used them several times before.

I myself used a lot of globals, specially when I started up. As an example, my first game had a global variable called timestep that stored the timestep throughout the game loop, to make sure all simulations were synchronous. That worked really well, and I, given the simplicity of my game, didn't really feel any need to do it differently and it was clocking around 250fps without the fixed frame duration (even though only 60 frames were rendered per sec). Later on, I decided to test it without the global, and refactored it in order to swap the timestep variable with a timestep() function, that was used to return the elapsed time since the last game loop. Believe it or not, I edited around 5 lines of code (using a little #define cheat to reduce the necessary changes) and gained almost 40% fps.

This was, of course, an extreme case, since my global variable was accessed by every simulation and animation, what means thousands of times a second.

Globals are really convenient, but that's all. They make our jobs, as programmers, easier on micro~small projects. But, despite of the comfort and convenience, they grant us nothing else. Specially considering that they are, in fact, slower, as the compilers go through a great deal to make them available everywhere. In my tests on college they where around 7x slower when compared to locals depending on its size.

The only situations where globals actually got faster than "not-globals" were extremely specific and unrealistic. It usually took a chain of function passing parameters through 15~20 functions with forced reallocation, compiler optimization off, and several signs of bad (not to say idiotic) design, but had to be made for testing sake.

This was by the design of the language, not by choice.

The design and architecture of the C++ language discourages the use of globals on most cases.


And if you have to use global variables, don't name them something as simple as x or y because then you'll accidentally collide with others variables named that. It will cloud what your intention was and sometimes you might be accessing the global "x' when you meant to access the local "x".

Well This is a Duh. Yes when using Global Variables you do your best not to use those same Variables as locals.

Let me state. That I Keep them in a simple use, nothing complicated. And I only use them in a controlled environment. and I think the way I originally stated their use is perfectly fine. If you disagree I am sure I will be hit for it , but if you agree.....Well fix it.

For(x=0; x<10;x++); < Controlled loop, Read Data, Check arrays

How many of you setup let us say your graphical view port with MAXWidth/MAXHieght ? Local or Global declaration ? How many time do you reuse these variables as Locals ?

The only advantage I can see this having is it saves you typing 4 characters (more for floats/other types) per for loop, excluding the first use.

The potential disadvantages are numerous, and many have been listed in this thread already. They can have serious problems and can in some cases be hard to find/isolate/fix.

Is your belief that the time saved by not typing "int " in a for loop is worth opening the yourself up to all those potential issues?

If so, I don't agree with your reasoning, and I would personally advise others against it.

Note that I'm not talking about the death of all globals here, I'm specifically addressing your use of global variables for loop counters, like your given example int x,y;

Hello to all my stalkers.


But I never had a problem with my use of globals and the way I use them.

Some things are generally a bad idea; there are exceptions, and they aren't always bad in 100% of cases, but in the overwhelming majority of cases they'll be a bad idea for most people. It's absolutely fantastic that you've avoided the potential problems, but that doesn't change the fact that there are a lot of potential problems and that the same habit is very probably a bad idea for others.

You're always free to do as you wish in your own code, but when you're giving advice to others you shouldn't take it as a personal attack when people offer a differing opinion -- especially when your own method goes against the normally recommended practice.

You've said that you've never personally had problems re-using global variables as loop counters, but you haven't actually suggested any advantages to doing so, whilst others have pointed out several potential disadvantages. Are there any potential advantages that lead to you preferring this specific technique?

- Jason Astle-Adams


and I think the way I originally stated their use is perfectly fine. If you disagree I am sure I will be hit for it , but if you agree.....Well fix it.

For(x=0; x<10;x++); < Controlled loop, Read Data, Check arrays
There's been several snarky remarks, but if you want an objective analysis:

Pro:

  • you save 4 characters per for loop ("int " before x)

Con:

  • You lose reentrancy for no good reason.
  • Any function with a for loop is unsafe to be used in recursive code.
  • Any function with a for loop cannot ever be thread-safe, because they're all sharing the same loop variables.
  • ^ The above taints the whole code-base, so the long-term code re-usability is harmed (if you ever are in a situation where you want to be writing recursive or multi-core code...)
  • You harm aliasing analysis, which harms performance. Becase 'x' is not a local variable, the compiler can't be sure how/when it changes. Any function in the body of the for loop could possibly modify 'x', so the compiler must be conservative and continually re-load the value of the 'x' variable from RAM each time it is used, instead of putting it in a register.
  • You harm data locality, reducing cache effectiveness, which harms performance. The 'x' value is not on the local stack with your other local variables, it isn't in the same memory location as any member variables you're using, in fact, it's off in some completely arbitrary memory location where your globals have been allocated, which means you're (as above: constantly) telling the cache to download some completely random cache line, which could potentially be evicting useful cache lines, such as ones containing objects that you're working with, or stack variables.
  • If you're working with other people, there's a good chance that they'll either use a member variable or a local variable that's also named 'x', which leads to confusing code where it's not obvious whether you're reading/writing to a local/member or a global.

This topic is closed to new replies.

Advertisement