Thread: About using global vars

  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    1

    About using global vars

    I read that global variables are not advised, so I have tried to use them the less I can, but there are always a few of them I need. Because I need speed code, I have the following question about global variables:

    1) Why are they not advised?
    2) Although I use they the less I can, what guidelines can I follow to use they in the best and efficient way?
    3) Does using the 'restrict' keyword when declaring the var be good in order to get faster global variable management code.
    4) Does has any sense to declare a global variable with the 'register' keyword?
    5) I have read global vars are reloaded after a function call. Is there anyway this can avoided (when we now for sure that the called function does not modify that var)?

    Thanks

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    We covered your first question recently in dark side of global variables.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by Tibor View Post
    2) Although I use they the less I can, what guidelines can I follow to use they in the best and efficient way?
    By not using them. Honestly, there is hardly any reason to use them. Most things can be accomplished by passing a pointer to a struct around.

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  4. #4
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    > By not using them. Honestly, there is hardly any reason to use them. Most things can be accomplished by passing a pointer to a struct around.
    Not always, they have their place...

  5. #5
    Registered User
    Join Date
    Aug 2008
    Location
    Belgrade, Serbia
    Posts
    163
    I agree with zacs. They are useful sometimes.
    Vanity of vanities, saith the Preacher, vanity of vanities; all is vanity.
    What profit hath a man of all his labour which he taketh under the sun?
    All the rivers run into the sea; yet the sea is not full; unto the place from whence the rivers come, thither they return again.
    For in much wisdom is much grief: and he that increaseth knowledge increaseth sorrow.

  6. #6
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by hauzer View Post
    I agree with zacs. They are useful sometimes.
    Which is why i said "Hardly any reason" and "Most things" In my opinion global variables are like using goto. It has it's place and can be useful, but for a beginner it's one of the most over-abused concepts.

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  7. #7
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    3) As far as I understand you declare a variable restrict, I think only pointers, when you know FOR SURE that it is the only pointer that points at some data. So you can gain some optimizations. I haven't used it ever. Dunno how useful it is. But if you are not actually sure that it is a restrict, you will get undefined behaviour. So it is not recommended.
    4) Well, as a standard rule DON'T use the register keyword. Except if you really know what you are doing. You just have to know that the compiler does this for you. It registers some variables in CPU registers in order to gain optimized code. How is not that simple.
    Registering a variable to a CPU register means that you narrow down the choices the compiler has to do its optimization.
    Generally the compile knows best and really does its job good (modern compilers at least). But I am sure there are some occasions that the user knows better, but those are rare.

    5) Reloaded in what sense?

    Generally, don't use restrict and/or register keywords

    1) All give you some quick ones
    * If not necessary don't use them. Meaning that if you can use local variables do so
    * Use really good names for global variables. If you want you can add a g_ in front of them just to tell people the variable is global.
    * If a function has 1 or two arguments and uses a global variable, maybe you should consider passing the variable by pointer and making it local in main.
    * If you modify 2-3 variables together, you can again make a struct and pass it by pointer to the function so you avoid global variables.
    * Use good names. No "x", "y".
    * Oh, and don't forget to use good names. Like "boardX", "boardY" for the coordinates of a board rather than "X", "Y".
    * If you actually use global variables a lot, consider giving them nice and readable names

    edit: Sorry for my grammar and syntax errors. Even more sorry for being (as always) bored to fix them
    Last edited by C_ntua; 12-12-2008 at 08:50 AM.

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    In a previous discussion about global variables and registers, the global register option (which by the way is not supported by the C standard - it is a gcc extension to allow this) did not only produce obviously worse code, but in some variants of the compilation, it even crashed the code (most likely because it is rarely used and some compiler bugs exist in this area). On a 32-bit x86 processor, there are SO FEW registers even without locking one down for a global variable, that the compiler is bound to make better use of the registers (unless of course you only have like three varaibles in your code, and you use this global variable in many places in many small functions). Some processors have many more registers so the penalty for locking a register to hold a global variable may be smaller - but it's still unlikely to give you any huge advantage except in very special circumstances.

    Yes, in general, global variables are reloaded after function calls. There is very little you can do to prevent this, as the compiler has no idea whether some global variable was modified by the called function or not unless it can see all of the called code itself and detemine for sure that there is no possibility that the code changes a particular (set of) global variable(s).

    This is the "you get bad performance from global variables" problem - there are other problems with global variables, but the "reload after calls" is definitely a performance (and potentially code-size) problem.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Does the compiler perform any optimization on this? Like check if the global variable is even used in the function?

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by C_ntua View Post
    Does the compiler perform any optimization on this? Like check if the global variable is even used in the function?
    It may do, but if it wants to use the register for another reason it will then have to SAVE the register and restore it again when it returns from the function (but then it probably would have to do that anyways, as you can only use "preserve" type registers for register globals - if you use one of the "these get destroyed when you call another function", any call to a C library function which isn't compiled specifically to know about the global would possibly destroy the global register content).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  11. #11
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by Tibor View Post
    I read that global variables are not advised, so I have tried to use them the less I can, but there are always a few of them I need. Because I need speed code, I have the following question about global variables:

    1) Why are they not advised?
    2) Although I use they the less I can, what guidelines can I follow to use they in the best and efficient way?
    3) Does using the 'restrict' keyword when declaring the var be good in order to get faster global variable management code.
    4) Does has any sense to declare a global variable with the 'register' keyword?
    5) I have read global vars are reloaded after a function call. Is there anyway this can avoided (when we now for sure that the called function does not modify that var)?

    Thanks
    They are not advised by some people because they "don't like them" here are some reason I found:-

    "a global variable can potentially be modified from anywhere"

    Well some people would say that's a bad thing but of course it is quite a good thing if
    you want to access them from anywhere isn't it!!

    What was from wikipedia, the other reasons they gave seemed a bit more unclear to
    me, words such as 'complexity' arose, butif something is complex, well it is gonna be complex, there is not much you can do about that, maybe you can shift that complexity
    from global variables to function calls and passing local variables but it is there nonetheless.

    I think it is a question of getting the right amount of global variables not trying to reduce them for the sake of it.

    But you can ask does the compiler or the microprocesser find global variables a problem?
    Answer no!!

    I normally just ask myself is this is a localised variable, because that is an easy question to answer.

    However if you want to write a program to be as fast as possible global vaiables will do that for you.

    I find most of the time it's fairly obvious what the scope of viable should be, but it is difficult to specify a general rule. I think it come down to will it be used often, do you know
    exactly where it will be used? If you don't my default is global.

    I find people who teach programming tend to waffle on about them endlessly, but unless you are talking about a specific program it is all rather meanngless ill defined waffle.
    How long is a piece of string stuff. Or like telling someone how to ride a bicycle, you will soon pick it up once you fall over a few times. It's much easier to learn by doing something then listening to someone explain it. (I find).

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by esbo
    Well some people would say that's a bad thing but of course it is quite a good thing if
    you want to access them from anywhere isn't it!!
    That is true, but such global objects should be rare in a well designed program. Note that global constants do not count here since they do not add state, hence it is easy to reason about them from anywhere in the program.

    Quote Originally Posted by esbo
    words such as 'complexity' arose, butif something is complex, well it is gonna be complex, there is not much you can do about that, maybe you can shift that complexity
    from global variables to function calls and passing local variables but it is there nonetheless.
    The idea is to manage the complexity by making it possible to reason about individual parts of the code.

    Quote Originally Posted by esbo
    I find most of the time it's fairly obvious what the scope of viable should be, but it is difficult to specify a general rule. I think it come down to will it be used often, do you know
    exactly where it will be used? If you don't my default is global.
    The correct default is to use local variables.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by laserlight View Post
    That is true, but such global objects should be rare in a well designed program. Note that global constants do not count here since they do not add state, hence it is easy to reason about them from anywhere in the program.
    They should be as rare or as common as they need to be.
    Quote Originally Posted by laserlight View Post
    The idea is to manage the complexity by making it possible to reason about individual parts of the code.
    The program runs as a whole, reasoning about a small part cannot tell you the overall
    effect.

    Quote Originally Posted by laserlight View Post
    The correct default is to use local variables.
    The only thing 'correct' about a program is whether it does what it is supposed to do.
    You can have all your variables correctly scoped and it can still fall over in a heap, or just not do what you intened it to do. Any 'correctess' beyond that is rather academic and a matter of ill defined opinion.
    If 'correctness' is something dreamt up by a third party, well that's a different matter, it depends who the third party is, if the third party is is me it is just whether the program does what it is supposed to do, no more no less. If it is you well you might require futher constraints.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by esbo
    They should be as rare or as common as they need to be.
    The reasons why global variables need to be as rare as possible (or more accurately, as rare as feasible, since it is always possible to do without them, but it may not be practical to do without them) have already been cited.

    Quote Originally Posted by esbo
    The program runs as a whole, reasoning about a small part cannot tell you the overall
    effect.
    Obviously. However, reasoning about small parts can help you reason about the program as a whole. You can liken this to proving a series of lemmas in order to prove a theorem (and in fact it is literally the case in formal verification of program correctness).

    Quote Originally Posted by esbo
    You can have all your variables correctly scoped and it can still fall over in a heap, or just not do what you intened it to do.
    That is true. You can also have all your variables poorly scoped "and it can still fall over in a heap, or just not do what you intened it to do". In other words, that good development practices do not guarantee correct programs does not mean that they should not be practiced. Poor development practices, such as the unnecessary use of global variables, merely make program correctness less likely.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    I find it easy to track the effect of a vairable in a progran simply my seaching on it in an editor. That is dead easy with a global variable, however when data is pass the name usually changes. This makes it much more difficult to follow like 10 times more difficult.

    The over use of local variable can make a program an absolute nightmare to follow.
    I have see it my self, the same variable changing names half a dozen times, it makes
    the program very difficult to follow.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. basic question about global variables
    By radeberger in forum C++ Programming
    Replies: 0
    Last Post: 04-06-2009, 12:54 AM
  2. Best way to avoid using global variables
    By Canadian0469 in forum C++ Programming
    Replies: 7
    Last Post: 12-18-2008, 12:02 PM
  3. Maintaining Global Vars Between Libraries
    By Canadian0469 in forum C Programming
    Replies: 9
    Last Post: 11-27-2007, 12:29 PM
  4. Global objects and exceptions
    By drrngrvy in forum C++ Programming
    Replies: 1
    Last Post: 09-29-2006, 07:37 AM
  5. Global Vars
    By ihsir in forum C++ Programming
    Replies: 4
    Last Post: 04-18-2002, 10:40 AM

Tags for this Thread