Theory Question: Global Variables
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 22

Thread: Theory Question: Global Variables

  1. #1
    Join Date
    Feb 2009
    Posts
    135

    Theory Question: Global Variables

    From what I've come to understand, we don't often use global variables because we want to preserve the name in case we wish to use it for a different, but similar purpose later on in the program. However, I've found in programming, that, at times, some variables only serve one purpose throughout the program and often have to be passed to function purely so they can be passed to other functions that need them and always because they need to use the same named variable, in a different spot.

    Wouldn't it make more sense then to put those variables in a header file and make them global?

    For example:

    Let's say I have a menu variable that contains all of the default menu attributes for a menu system, or a character variable that records every aspect of a character. Rather than reference the variable everywhere, why not make it global?

  2. #2
    Join Date
    Aug 2007
    Posts
    858

    Re: Theory Question: Global Variables

    Really the main reason for avoiding global variables is to avoid global state. It can make your program more difficult to debug since a global can be modified from literally anywhere in the program. It can make it difficult to reuse code, since it isn't going to be clear what globals are required for code to work correctly. It can also lead to "lazy" designs that are more difficult to modify or maintain. Take your character example for instance - what if you decide later that you want to have two characters instead of one? 5 characters? A random number? Since all of your code dealing with characters is tied to this global variable, now you're going to have to go back and modify all of it in order to support the new design.

    Now, there are some people who religiously hold the view "no globals at all, ever, period, no exceptions", but most people tend to agree that there are times when it's simply easier to use a global and be done with it. For example, cin and cout in the standard library are global stream objects. It's also common to see things like loggers set up using globals.

  3. #3
    Join Date
    Nov 2006
    Posts
    1,611

    Re: Theory Question: Global Variables

    I echo Speedo's points.

    I'd like to add this to the perspective.

    When decided what classes to fashion, it's instrumental to keep in mind that they model or represent concepts as metaphors. The more 'real' we can make that metaphorical representation of concepts, the more like a machine our software becomes - the properties of components fitting together to create a larger machine.

    Global variables violate this notion of encapsulation. If they're genuinely appropriate as global variables, it would be because these variables represent global concepts - that for which there can be only one for the entire application.

    If the concepts these variables might not always be global, as speed points out, then at best they should be members of an object which we instantiate once. This encapsulation makes them portable as a group into other environments which aren't always global in concept. That is, they may be global in a simple application, but not always global in future developments.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

  4. #4
    Join Date
    Nov 2008
    Location
    England
    Posts
    748

    Re: Theory Question: Global Variables

    The biggest problem with global variables is they increase coupling and impede code modularity. This makes it much harder to reuse code using globals. If the value of a global variable cannot be worked out at compiletime and instead is initialised at runtime there can also be initialization order issues.
    Basically you should try to avoid using globals as much as possible. What you see now as convienience, may in fact be a complete headache as your project grows larger.
    Get Microsoft Visual C++ Express here or CodeBlocks here.
    Get STLFilt here to radically improve error messages when using the STL.
    Get these two can't live without C++ libraries, BOOST here and Loki here.
    Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
    Always use [code] code tags [/code] to make code legible and preserve indentation.
    Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.

  5. #5
    Join Date
    Feb 2009
    Posts
    135

    Re: Theory Question: Global Variables

    I guess I'll learn from my mistakes and try it out. I do think in this instance it will work. But I think I'm of some of the same mind in why they are bad, though I haven't run into many issues yet still being new to the coding thing.

  6. #6
    Join Date
    Feb 2009
    Posts
    135

    Re: Theory Question: Global Variables

    Update: I'm getting all sorts of errors when trying to turn the variable global. It's frustrating enough to make me want to stop since I know people are going to be hesitant to help me get them working since people are against them in the first place.

    My question is: Is it common practice to see variables in a program that go in almost every function just so that they can be passed to other functions just because they are so relevant as a variable? That seems needlessly inefficient for variables that you know there is only ever going to be one instance of across an entire program.

  7. #7
    Join Date
    Apr 1999
    Posts
    27,444

    Re: Theory Question: Global Variables

    Quote Originally Posted by BleaS View Post
    Update: I'm getting all sorts of errors when trying to turn the variable global.
    What are the errors.
    It's frustrating enough to make me want to stop since I know people are going to be hesitant to help me get them working since people are against them in the first place.
    Why not show your code? You've just described what you're doing, but none of us know exactly what you are trying to do.
    My question is: Is it common practice to see variables in a program that go in almost every function just so that they can be passed to other functions just because they are so relevant as a variable?
    No.

    Good C++ programmers encapsulate that entire design into a class or several classes. If such a variable is so important to an entire program, it begs the question of why the "program" is not a self-contained class or set of classes, where that global is just a member variable.

    It sounds like you should be creating a class instead of "globalizing" your application.

    Regards,

    Paul McKenzie

  8. #8
    Join Date
    Feb 2009
    Posts
    135

    Re: Theory Question: Global Variables

    Quote Originally Posted by Paul McKenzie View Post
    What are the errors.
    Why not show your code? You've just described what you're doing, but none of us know exactly what you are trying to do.
    I can.

    Code:
    Character.h
    
    #ifndef GUARD_Character_h
    #define GUARD_Character_h
    
    extern struct Character {
    	int Curr_x, Curr_y;
    } Curr_Char;
    
    #endif //GUARD_Character_h
    
    
    Character.cpp
    
    #include "Character.h"
    
    Character Curr_Char;
    
    Curr_Char.Curr_x = 0;
    Curr_Char.Curr_y = 0;
    Errors:
    Code:
    character.cpp(5) : error C2143: syntax error : missing ';' before '.'
    character.cpp(5) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
    character.cpp(5) : error C2371: 'Curr_Char' : redefinition; different basic types
            character.h(6) : see declaration of 'Curr_Char'
    character.cpp(6) : error C2143: syntax error : missing ';' before '.'
    character.cpp(6) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
    character.cpp(6) : error C2371: 'Curr_Char' : redefinition; different basic types
            character.h(6) : see declaration of 'Curr_Char'
    Good C++ programmers encapsulate that entire design into a class or several classes. If such a variable is so important to an entire program, it begs the question of why the "program" is not a self-contained class or set of classes, where that global is just a member variable.

    It sounds like you should be creating a class instead of "globalizing" your application.

    Regards,

    Paul McKenzie
    I'm in the process of learning, I don't know anything about classes yet. However, I am at a point where I can do things that seem to suggest the use of something like a global variables.

  9. #9
    Join Date
    Mar 2009
    Location
    Riga, Latvia
    Posts
    128

    Re: Theory Question: Global Variables

    Best practice:
    Try to localize variables. Make them as local as possible.

    For more info I'll recommend to read Shatter & Alexandrescu books and Allen Holub's Enough Rope to Shoot Yourself in the Foot. Mr Holub, for example, recommends to limit the number of global variables to about ten.

    From my modest knowledge and experience
    1) When programming for WinAPI it makes sense to make hThisInstance and hDllInstance global i.e. copy thier values into g_hThisInstance and g_hDllInstance respectively.
    2) If you worry about intensive stack usage when dealing with recursion put the function to separate module and make the arguments static.
    Important note /need multithreading guru help/:
    It also seems me that using global variables makes your code multithreading-incompatible.
    3) You could use static fields of classes.
    4) Then dealing with huge number of global variables you need strict naming conventions. Then you localize your identifiers you shouldn't worry about that as C++ doesn't allow to create identifiers with :: and . inside.

  10. #10
    Join Date
    Mar 2009
    Location
    Riga, Latvia
    Posts
    128

    Re: Theory Question: Global Variables

    Try this:
    Character.h
    Code:
    ...
    typedef struct
    {
        int Curr_x, Curr_y;
    } Character;
    ...
    Character.cpp
    Code:
    ...
    Character Curr_Char;
    ...
    You should to know the things I've omitted.

  11. #11
    Join Date
    Feb 2009
    Posts
    135

    Re: Theory Question: Global Variables

    The major issue for me is that I find myself passing certain variables through EVERY function, even if the nature of the function doesn't seem to involve them. Just because it needs to go to another function.

    It didn't seem efficient or what coders would stand for. But, from what I understood, the answer was classes. Classes aren't what I know yet, not for a few chapters. But I need to practice what I do know as much as I can, and I want to do it making programs that are interesting to me, so sometimes I have to go beyond what the book gives as an example. However, I know everything I need to make this program, the issue is trying to go a further step and not waste my time on redundancies.

  12. #12
    Join Date
    Apr 1999
    Posts
    27,444

    Re: Theory Question: Global Variables

    I'm in the process of learning, I don't know anything about classes yet. However, I am at a point where I can do things that seem to suggest the use of something like a global variables.
    The title of the thread is a theory question on global variables. The answers given to you so far all state to only use globals if necessary, and if so, to sparingly use them.

    What you are describing, having to pass a variable to certain function, is what classes are designed to solve. That variable would have been a member of a class, and then you don't pass anything around since that variable is part and parcel of the class you're implementing.
    The major issue for me is that I find myself passing certain variables through EVERY function, even if the nature of the function doesn't seem to involve them. Just because it needs to go to another function.
    Then learn classes. Again, that is the real solution to the problem you're describing.

    What you're stating is no different than this scenario:

    You write a program that declares 100 integer variables, say int1, int2, int3, int4, ... int100. After you write the program you say (justifiably) "this is very tedious work doing the same thing for 100 integers -- could I use #define macros to make the code easier?". One of us would say to you "learn arrays and indexing, not macros". So you learn to use arrays and indexing -- you shouldn't continue using 100 separate integers just because simple types are the only thing you happen to know at the moment and you may have read something on #define.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; August 9th, 2009 at 01:56 PM.

  13. #13
    Join Date
    Feb 2009
    Posts
    135

    Re: Theory Question: Global Variables

    Arrays seem a bit less complicated than learning classes. It doesn't seem to be reasonable to skip the learning progression to learn classes when they're much more to deal with and complicated than learning to use arrays over 100 integers.

    I think, now understanding what people are using, that I will simply stick to passing through the variable in every function. It sucks, it wastes time, but it will motivate me to keep learning until I get to classes, and being able to move past rudimentary, novice coding.

  14. #14
    Join Date
    Apr 1999
    Posts
    27,444

    Re: Theory Question: Global Variables

    Quote Originally Posted by BleaS View Post
    Arrays seem a bit less complicated than learning classes. It doesn't seem to be reasonable to skip the learning progression to learn classes when they're much more to deal with and complicated than learning to use arrays over 100 integers.
    You're missing the point.

    The point I'm trying to make is that there will always be cases where something you learned will not work efficiently until you actually learn the correct way to solve the problem. It could be something simple as arrays, or as complex as policy-based programming using templates.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; August 9th, 2009 at 02:02 PM.

  15. #15
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,891

    Re: Theory Question: Global Variables

    Until you actually learn classes, you can simulate a class object using global variables if:

    1) You clearly demarcate a set of related functions which will use each global, and allow no others to do so.

    2) If the set of functions needing access to a value is not conceptually groupable, consider whether writing a getVarName() function which offers read-only access to a global allows you to limit the set of directly-accessing functions to the point where they do form a clear conceptual group of operations. (Read-only access to a global int, for instance, could be achieved by returning a "const int&" from the function. Likewise for any type.)

    3) Your conceptual function grouping can be thought of as a single object, machine, or agent in the system. Don't worry about precise definitions----it just needs to represent a "thing which does stuff." It should be conceptually possible to have more than one of these things, but you cannot support actually having more than one until you start using classes.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center