Sign in to follow this  

Globals usage in tutorials and elsewhere.

This topic is 1511 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have been reading the OpenGL Programming Guide, and in it they justify usage of global variables in tutorials on the grounds that they are just small programs in the examples. The question I have is if there is some piece of information about global variables that I don't understand that would justify that? I am familiar with scope, but I am trying to understand why you would risk the possibility of teaching something that is considered to be bad practice (as far as I have ever heard; also, I realize that the book I am referring to is not to teach programming, but OpenGL), when you could just avoid using the globals?

So in essence, is there a difference that I simply am not understanding that makes their use appealing for such tutorials?

 

When I took a course in computational physics, the professor seemed to love global variables, and it took me a bit to get past that, as I had read often that one should avoid them. Every C program that we looked at in class had almost every piece of information related to the values of the elements of the simulation placed in variables that were at the top of the source file, right below the includes and defines. I believe that I read that C variables are not actually strictly globals in that context, so my usage of the term may be incorrect.

Share this post


Link to post
Share on other sites

I have been reading the OpenGL Programming Guide, and in it they justify usage of global variables in tutorials on the grounds that they are just small programs in the examples. The question I have is if there is some piece of information about global variables that I don't understand that would justify that? I am familiar with scope, but I am trying to understand why you would risk the possibility of teaching something that is considered to be bad practice (as far as I have ever heard; also, I realize that the book I am referring to is not to teach programming, but OpenGL), when you could just avoid using the globals?

So in essence, is there a difference that I simply am not understanding that makes their use appealing for such tutorials?

 

When I took a course in computational physics, the professor seemed to love global variables, and it took me a bit to get past that, as I had read often that one should avoid them. Every C program that we looked at in class had almost every piece of information related to the values of the elements of the simulation placed in variables that were at the top of the source file, right below the includes and defines. I believe that I read that C variables are not actually strictly globals in that context, so my usage of the term may be incorrect.

 

globals aren't problematic for small code samples so for a tutorial that focuses on something other than programming there is nothing wrong with using them.

Share this post


Link to post
Share on other sites

Also, in games you often use the equivalent of Globals, except you keep them encapsulated in an enumeration or namespace. They have real uses in game development, so I wouldn't fret too much.

 

Cheers :)!

Share this post


Link to post
Share on other sites

Globals are problematic when you may have issues of naming, multiple simultaneous accesses and manipulation, variables with a high load of usage in general (globals aren't as fast as a local variable, depending on your compiler), harder to keep track (need a namespace). If those problems with the global variables don't affect you for some reason, they may be useful sometimes.

 

Still, you can use globals for simple code samples, classes and tutorials since they give a huge edge on readability. It would be bad if you had to keep track of lots of references, pointers values, if you added 3-4 parameters to each function, just to avoid a global on a code snippet; where you, btw, wanted to teach something that had nothing to do with globals.

 

For an example, if I want to teach you how to implement a concatenate strings function in C++, it could be useful to use the namespace std globally (string is more readable than std::string), and you could pass less references as parameters to functions, also adding to the readability on a short code.

 

About your question of them being or not global due to their position, someone please correct me if I'm wrong here, it depends on the file type and usage of the code.

If you have a global variable inside a .h header, it'll be available at any place where that header was included. Differently, if you include it inside an implementation file such as .cpp, they'll be "global in that file".

Share this post


Link to post
Share on other sites

OMG - This was just a simple opinion on the use of Global Variables.  I have come across some languages that the only way you could use arrays was to make them global.

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

  Besides,  to globalize or localize is a personal programming choice in most cases.  Normally dictated by the size of the program and their use.

  But I guess my original comment on this became a game of hangman's Noose

Edited by Poigahn

Share this post


Link to post
Share on other sites

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 used to do this, thinking it was a clever way to save space, so believe me when I say don't!!! You cannot conceive of every way in which you might call a function, so don't expose its inner workings to the global scope! Good practice in software design is to reduce the affect a piece of code can have on other pieces of code.
 
As an aside I actually ran into this exact problem today. Javascript will put a variable in the global scope if you don't explicitly put 'var', so all of my loops used the same variable "i" unintentionally. Not fun to debug. =)
 

 

I believe that I read that C variables are not actually strictly globals in that context, so my usage of the term may be incorrect.

Variables in C declared outside of any functions are global in scope.

 

I would like to point out to all those who blindly discourage the use of globals, that cout is a global. Globals have their place, but can be very easily misused.

Edited by Segmented

Share this post


Link to post
Share on other sites

Ah yes. Global loop counters are great. If you want slow code that accesses memory rather than keeping the counter in a register and want to see everything go up in flames the moment you add multiple threads into the mix.

 

Simple rule: keep the scope and lifetime of variables as small as possible.

 

-Don't declare stuff at the beginning of functions, especially if they are a) only used way further down or especially b) within a single block or branch.

-Don't make variables members that are only used in a single function or could easily be passed as parameter

-Do not make anything global, unless the alternative would be even worse

-To avoid name conflicts, don't use overly short names on variables with large scope (a global should never be a single letter)

Share this post


Link to post
Share on other sites

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.


Pretty pretty please tell me it is April 1st..... Or some other joke day, I simply don't believe this was a serious comment. The only way I can read it is as satire.

Share this post


Link to post
Share on other sites

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

Edited by Serapth

Share this post


Link to post
Share on other sites

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

Edited by Eck

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites


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 ?

Share this post


Link to post
Share on other sites


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.

Share this post


Link to post
Share on other sites

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.

Edited by Paradigm Shifter

Share this post


Link to post
Share on other sites

 

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.

Edited by dejaime

Share this post


Link to post
Share on other sites

 


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;

Share this post


Link to post
Share on other sites


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?

Share this post


Link to post
Share on other sites


Globals are problematic when you may have issues of naming, multiple simultaneous accesses and manipulation, variables with a high load of usage in general (globals aren't as fast as a local variable, depending on your compiler), harder to keep track (need a namespace). If those problems with the global variables don't affect you for some reason, they may be useful sometimes.

I may have asked the question in a bit unclear fashion, but one of the things that I was interested in was things such as the stated speed difference between local and global variables. The impression that I have gotten from responses is that a lot of the matter lies with what you are writing the program for.

If I were to attempt to delve into the details of why these differences occur, would some of this be the memory system? I feel like it is a rough way to ask the question; would it be more specifically the way that the specific language deals with handling memory?

I am more than happy to use google myself, but if anyone is familiar with any good resources off the top of their heads (I don't consider it anyone's responsibility to find it for me, but if you are already familiar with something it would certainly make it easier, lol), that would be a good starting point, it would be appreciated.

Share this post


Link to post
Share on other sites
No, it's to do with 'computer architecture' (specifically, the CPU cache and 'locality of reference') rather than language.

The other issue I mention was aliasing, which is something that compilers have to care about when optimizing.
http://en.m.wikipedia.org/wiki/Aliasing_(computing)

These things don't mean than "globals are slow" -- members or arguments can suffer from the same issues.
You've got to do a case by case analysis on any piece of code to figure out if/why it's slow, which isn't really a for beginners topic ;)

Share this post


Link to post
Share on other sites

This topic is 1511 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this