Thread: Global Varibles

  1. #31
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by modwind View Post
    That is true, so every global data should be a class with functions to access its contents. The functions allow to control simultaneous access from different threads and can check data for validity before changing a global state.
    Any variable, or object, only supports a finite set of operations. Making a global object (and controlling access to its internals) versus making data global does not change that.

    Controlling simultaneous access to a global resource from multiple threads, in itself, increases complexity. Of the functions controlling that access, at the least.

    One common trap with multithreaded programming - which novices invariably run afoul of, without realising it - is that no object can protect itself from concurrent access. Something else (an object or a function at a higher level of abstraction) must protect the object.

    Quote Originally Posted by modwind View Post
    Almost any complex program has global data.
    That is not true. It is true that the presence of global data, in itself, increases the complexity of code that interacts with that global data. Or it increases the amount of analysis to put bounds on what state the global data is in, at any point in time.

    The most complex programs I have seen did not have any global data (and, no, they did not use dynamic memory allocation after completing their startup/initialisation). Their complexity would have been increased, and their maintainability made more difficult, if they had made use of global data.

    Quote Originally Posted by modwind View Post
    It is too hard to pass pointers between functions all the time.
    In a professional setting, whenever I have seen folks use an argument like that, I ask them to describe the architecture of their code. And I have only ever found one person making such a claim who could actually describe their architecture.

    I see it more in amateur settings (such as people doing homework exercises). In an amateur setting I'll concede that simple programs can sometimes be made simpler by using global data rather than passing arguments. However, that principle does not scale to large programs.

    Yes, it may take more typing to pass arguments to a function, or to specify data structures that can be used to supply non-trivial data as an argument to a function. But it is also harder to get a complex program running correctly when multiple functions make use of global data.

    Quote Originally Posted by modwind View Post
    They may be less global. Imagine the program itself is a class. As any other class it has members that you can access. The Program is singleton, there is only one instance and you can't create more. That instance lives while application executes.
    Data is global if it pertains to the whole program. Or it is not. There is no intermediate concept. So it is not possible for a variable to be "less global" than another variable.
    Last edited by grumpy; 03-04-2012 at 03:46 AM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  2. #32
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by motocross1 View Post
    Also (FYI)... my code is very similar to:
    WIN32API code: Listview control
    Just more windows and feature (as in 10000 lines of code).
    But there are no globals in that! (unless you accept phantamotap's premise, in which case there is one #define).

    Quote Originally Posted by modwind View Post
    That is true, so every global data should be a class with functions to access its contents.
    That is a terrible idea. For one thing, it only superficially deals with the problem of organization. For another, it does not deal at all with the more significant issue, which is that code which relies on global data is brittle: it will break easily, and when it breaks it is harder to debug. It is also awkward or impossible to extend and adapt, and more limited in re-usability.

    It is too hard to pass pointers between functions all the time.
    It is not hard to pass pointers.
    Last edited by MK27; 03-04-2012 at 08:22 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #33
    Registered User
    Join Date
    Feb 2010
    Posts
    98
    If data inside a function will be used most every time the function is called, you make it static. That static data "exists" as long as the application is running. Any code inside that function can change the value of that static data. The more blocks of code that access that static data the more complex the function.

    Sounds similar to global to me.
    Oh but wait, you should "only use data passed into the function".
    Meaning, you should also "not" use static data then, right?
    Gimme a break.

    There ARE times to use static data.
    And...
    There ARE times to use global data.

    And, there ARE people who are born gay.
    And, there ARE times to get an abortion.

    To flat out say "all globals are wrong" is nothing more than religion.

    Brainwashed zealots will always parrot what they have heard others preach.
    Religious nuts will always ignore a person's needs in order to pimp their own doctrines.
    The holier-than-thou will always call people "evil" and "sinners" to make them feel guilty.
    And you don't want to be evil in God's eyes, do you?
    Amen. Amen. Amen.
    If you use globals, you are "lazy" and your code "lacks design".
    And you don't want to be an "amateur" in the eyes of the professionals, do you?
    Like. Like. Like.
    Hmmm, exactly.

    (you guys wanted a debate, I'm just keepin it real)

    Now pay close attention...
    It's my opinion that, all losers are smokers.
    Say what?
    You think I said, all smokers are losers.
    But I did not say that at all.

    You see, there's a problem with human thought.
    So although it is true that, most amateurs overuse globals.
    It is NOT true that, someone who uses globals is an amateur.
    Get it?

    Summary:
    Everyone should quit thinking, "Oh, but what will others think of me?"
    If you are gay, it sometimes just makes sense to not try so hard making yourself not-look-gay.
    If you really need to access data globally, it sometimes just makes sense to not try so hard to make it look like you don't.

    **GLOBALS ARE OKAY**

    Anyway, back on topic...
    I finally found some answers to my original question:
    http://google-styleguide.googlecode....k/cppguide.xml
    http://www.state-machine.com/doc/AN_...g_Standard.pdf
    (not that anyone here really cares)

  4. #34
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    But there are no globals in that! (unless you accept phantamotap's premise, in which case there is one #define).
    Actually, it doesn't even have global state according to my standard.

    The define is only used in one function making it what I would call a label.

    To flat out say "all globals are wrong" is nothing more than religion.
    Yes; we all worship at the alter of "Don't let convoluted interrelationships make your code a maintenance nightmare."

    *dusts hands off*

    I'm out.

    Soma

  5. #35
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Philosophy abuse! Philosophy abuse!

    Quote Originally Posted by motocross1 View Post
    Sounds similar to global to me.
    Oh but wait, you should "only use data passed into the function".
    Nobody said that. By that reasoning, you shouldn't declare any variables (data) inside the function, static or otherwise. Making the source of the data passed in sort of paradoxical...

    Static variables are things to be used carefully, but they do have a use. And they are not globals.

    And, there ARE people who are born gay.
    This is confusing identity with behaviour. Most likely (or at least, quite possibly) there are people who are born gay. But no one was born to use global variables.

    And, there ARE times to get an abortion.
    Okay, but usually not because you planned to get pregnant, figuring this is (another?) good time for an abortion. Practically no one would want to make it a regular practice. Like, "Abortion? All the time! It's not a bad habit, really."

    To flat out say "all globals are wrong" is nothing more than religion.
    No, the cornerstone of religion is faith, which is why religious people get to claim just about anything with impunity by claiming it is the will of a divine being who's existence is inherently unprovable. The cornerstone of saying using globals leads to bad design is reason. I understand that it may sound a little bit like you are being told "because God said so" if you don't grasp the reasons, but in fact, those are not articles of faith, they're rational assertions.

    You are free to do what you like, but here's a promise: if you stick with programming seriously, at some point in the future you will remember this little debate and wonder what the beejezus you were trying to defend.

    Brainwashed zealots will always parrot what they have heard others preach.
    I can see what you mean, but keep in mind, I don't see any programmers with significant experience arguing against the idea that the fewer the globals, the better. So like, 0 would be the ideal number. Likewise, go pick a school and find a prof who isn't also going to tell you the same thing.

    There's a reason for that which I've tried my best to explain, but I can't really add more to it if you consider this an argument and so respond with counter-points instead of questions.

    I guess I respect you for having the courage of your convictions, if you think this is a "the emperor wears no clothes scenario". But do yourself the favour of trying, in the future, to entertain the idea that your globals might not be making life easier. I think eventually you'll start to get why. Is that condescending, lol?

    The holier-than-thou will always call people "evil" and "sinners" to make them feel guilty.
    And you don't want to be evil in God's eyes, do you?
    If you use globals, you are "lazy" and your code "lacks design".
    And you don't want to be an "amateur" in the eyes of the professionals, do you?
    Hell no. But conversely, you should not reject the idea that the professionals might have something to offer for fear of seeming like you are just trying to suck up or something.

    (you guys wanted a debate, I'm just keepin it real)
    Pretty sure us guys actually didn't want a debate, really. People are trying to help you. It is not about

    EGO
    Last edited by MK27; 03-04-2012 at 02:36 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #36
    Registered User
    Join Date
    Feb 2010
    Posts
    98
    I don't see any programmers with significant experience arguing against the idea that the fewer the globals, the better.
    For the record, I agree the fewer the better - I strive for none.
    But, in my current project, it makes sense to use them.
    To wrap it up in a pink ribbon and claim it is not global data would be contrived.
    Besides, tracing the flow of a global is simple - trying to trace pointers to classes to pseudo-globals is not.
    Honestly, some people's classes are so illogical you can barely follow them.
    I think they must get paid per hour to write that junk.
    I strive to KISS while having it written professionally.
    It's my project, my code, my app, it's just for me - not a corporate project group of programmers.
    Meaning, I am allowed to do what makes sense.

  7. #37
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Take writing, for example. Ernest Hemingway may have been able to write a sentence fragment and get away with it, but most of us can't. You shouldn't start breaking the rules until you have an extremely good understanding of why they are there in the first place. You're nursing bad habits and wasting valuable time which could be spent growing as a programmer.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  8. #38
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by motocross1 View Post
    For the record, I agree the fewer the better - I strive for none.
    But, in my current project, it makes sense to use them.
    Especially if you've already written 10,000 lines or something, lol. Then you're in the same boat as me with that earlier project I mentioned. I'd have to re-write it. Maybe I will eventually :/.

    But: from now on, when you start a new thing, humour the established wisdom a bit and try writing stuff with no globals at all. At first, this may just amount, as you say, to passing pointers around between stand alone functions, but gradually you'll start to see other possibilities, vis, how classes and objects relate to one another. Particularly if you go a step further and try to minimize the use of stand-alone functions (like, don't use any unless you are using an API that demands it, eg, with strictly defined callbacks).
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #39
    Registered User
    Join Date
    Feb 2010
    Posts
    98
    good understanding of why
    humour the established wisdom
    Fine, I would love to hear real reasons why globals are bad then, especially app bool's and configs.
    (I'm not picking a fight, I'd really like to know)

  10. #40
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by motocross1 View Post
    Fine, I would love to hear real reasons why globals are bad then,
    Hmm. The points have already been made, but since you still don't buy it, I'm trying to think of how to make it clearer.

    Encapsulation is the basis of object oriented programming. Encapsulation means that an object is a black box. What happens inside the box does not matter to what happens outside the box, and what happens outside the box does not matter to what happens inside the box. The only relationship between the inside and the outside is the public interface. This is true even with regard to objects within objects, because all the containing object can do to the contained object is what it can do via the public interface.

    Using globals violates this, because the global data is not part of the object, and now it's inside. But so what?

    For one thing, if your class depends on that, that class is now bound intrinsically into your program. You can't take it and use it somewhere else without having to drag the framework of global state it now depends on. Of course, not every class has the potential for re-use anyway, so who cares? Two points:

    1) If some of the objects in your program are entangled with global data, chances are all or most of them then have to be, because that's how you're passing information. If that isn't the case (eg, if in fact only a few of the classes do this) then that data doesn't need to be global, it should be part of one of the relevant classes. If it is the case, then you've thrown out the possibility of code re-use for no good reason.

    2) Even if you don't think there is going to be anything worth re-using, it is worth trying to write as if there might be. At least then there is some chance you'll end up with something that is, and in any case, that's the direction your skills will develop in (toward the open road, as opposed to into a dead end). You're working on a GUI. Consider the library you are using. It is all re-usable parts. I've never seen a GUI API that didn't obviously present opportunities for taking these (lower level) parts and assembling them into higher level classes or components that could also be used in a wide range of circumstances. That's where stuff like combo boxes, tree-views, etc. came from. It is better to have a hierarchy going from the small and general to the large and particular in steps than simply taking all the littlest bits and assembling them into a monolithic whole. The incremental hierarchy is much easier and fun to play with than the monolith.

    especially app bool's and configs.
    These things belong inside, not outside, a class. There's nothing wrong with a singular object representing, say, the application. That is par for the course with GUI stuff, I think. But not, as modwind suggests, encapsulating the entire program; there is a difference, since the program includes handlers relating the application to the OS, as in the listview example you posted. Which like I said, has no globals at all.

    Such an object is not global; it starts in main(), like the listview example. You've said repeatedly you don't see a difference, but there is. The only reason to make it global is because you want to try and reference it from anywhere, which breaks the encapsulation of where ever that is, and makes chaos of the program's flow. If you don't want to do that (and you shouldn't), then the object needn't be global.


    I notice you've consistently argued that you don't see how globals create a debugging problem. The reason they make chaos of the flow is because, just as you eliminated the possibility of class re-use by incorporating globals into it, you've also eliminated the possibility of working with discrete, independently structured parts. The hands down, #1 reason OO languages like C++ are so widely used is because of the black boxing facilitated by class encapsulation. This makes the difference between a program that can grow (they always end up bigger than you think) manageably and a program that hits a wall of painful (and unnecessary) complexity. OOP simplifies. This is why a lot of people consider C too difficult to use for large projects (it's harder to keep your design clean).

    Okay now I'm hungry...
    Last edited by MK27; 03-04-2012 at 05:40 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  11. #41
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Read this link Coupling (computer programming) - Wikipedia, the free encyclopedia
    Global variables increase coupling; Coupling is defined as bad in programming.

    I use Global variables on a regular basis because I do embedded C programming; there is no real readable other option other using Global variables (lack of stack space).
    Note: I do use pointers to pass the global around to most of the functions that need them.
    Note: I could get rid of my Global variables; but it would make the code harder to read and maintain.
    You might have a similar case; but without more info, I consider it very unlikely anyone will agree with you.
    Therefore, your post is reading like you are either very ignorant or an troll.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  12. #42
    Registered User
    Join Date
    Feb 2010
    Posts
    98
    I could get rid of my Global variables; but it would make the code harder to read and maintain.
    Finally, someone said it. Thank you very much.

    Encapsulation - sure, re-usable parts are great.
    There's no need to copy-n-paste Part1 and call it Part2, just create a class instead.
    But, if I packed everything into class "boxes" I'd have 20000 lines of code.

    Coupling - you better believe it.
    Every bit of my code is HIGHLY coupled with isLoggedIn, etc.
    If it is "bad" then that's too bad.

    Now then...

    I would like to make a suggestion.
    I suggest programmers should focus on what's important, as in, not those high-minded concepts.

    There is only a few REAL goals in computer programming (C++, Java, PHP, Perl, etc.)
    1) Perform the main task efficiently by performing all subtasks efficiently.
    2) Run without error or memory leaks.
    3) Be easy to read and understand.

    Hmmm: global_isLoggedIn=true;
    Well, that's easy to understand.
    Success. I have my method now.

    Of course, 3 is optional if the complexity increases speed and you are a programmer at a HFT firm.
    Otherwise, if you are successful with 1, 2, 3, then it is as easy as it should be.
    Surely you all can agree with that.

  13. #43
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by motocross1
    I would like to make a suggestion.
    I suggest programmers should focus on what's important, as in, not those high-minded concepts.

    There is only a few REAL goals in computer programming (C++, Java, PHP, Perl, etc.)
    1) Perform the main task efficiently by performing all subtasks efficiently.
    2) Run without error or memory leaks.
    3) Be easy to read and understand.
    However:
    • Global variables make it more difficult to verify #2.
    • Beyond small programs, global variables make #3 difficult to achieve.


    These are things that people have been trying to tell you in this thread, but it looks like you have made up your mind and were just looking for someone to agree with you, ignoring the fact that the agreement is only for special cases ("embedded C programming" with "lack of stack space").

    I would like to make a suggestion. I suggest that you stop taking things out of context, wake up your idea and make an effort to understand what people are trying to tell you.

    EDIT:
    Quote Originally Posted by motocross1
    Encapsulation - sure, re-usable parts are great.
    There's no need to copy-n-paste Part1 and call it Part2, just create a class instead.
    But, if I packed everything into class "boxes" I'd have 20000 lines of code.
    If your program really needed to be 20000 lines of code long with appropriate use of classes, then using global variables instead would not help you because there is an inherent amount of work to be done that abstractions such as classes would make it easier to implement. You are attacking a strawman by saying 'packed everything into class "boxes"'. (Oh, and mind you, 20000 lines of code is not particularly impressive beyond the realm of school/hobby projects.)

    Quote Originally Posted by motocross1
    Coupling - you better believe it.
    Every bit of my code is HIGHLY coupled with isLoggedIn, etc.
    If it is "bad" then that's too bad.
    Yes, it is too bad. I believe that you are just exaggerating with "every bit", but in any case, with your attitude, you are simply a bad programmer. I hope that I will never have to do a project with you, or use anything that you write.
    Last edited by laserlight; 03-04-2012 at 08:25 PM.
    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

  14. #44
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Quote Originally Posted by motocross1 View Post
    There is only a few REAL goals in computer programming (C++, Java, PHP, Perl, etc.)
    1) Perform the main task efficiently by performing all subtasks efficiently.
    2) Run without error or memory leaks.
    3) Be easy to read and understand.
    You forgot maintainability.
    The use of Global variables likely means your code is hard to maintain.

    Note: Writing cold on an Micro-controller is NOT what you are doing.
    Is your code really more readable?
    Is your code really more maintainable? I would guess no.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  15. #45
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by laserlight View Post
    (Oh, and mind you, 20000 lines of code is not particularly impressive beyond the realm of school/hobby projects.)
    Add an extra zero to that, and we might be at the low end of the realm that I would describe as moderate size.

    Practically, I consider lines of code as a very poor measure of program size. I prefer measures such as man-years of development effort. I consider a small program as the result of less than ten or fifteen man-years of effort (not counting the development effort associated with reused or third-party libraries).


    Quote Originally Posted by laserlight View Post
    Yes, it is too bad. I believe that you are just exaggerating with "every bit", but in any case, with your attitude, you are simply a bad programmer. I hope that I will never have to do a project with you, or use anything that you write.
    I agree.

    As food for thought, for motocross1, I will describe a little scenario that occurs on occasion in the real world.

    Imagine you and the small (twenty-person) team of which you are a member have spent the last couple of years designing and developing a system for a customer. The code makes fairly regular usage of static variables, to avoid passing program state around. At last count, there were about 100 functions that manipulated or checked that global state, and those functions are called by many other functions. The customer is subjected to regulatory constraint, and must engage an independent reviewer to assess if the system is fit for the intended purpose, and also determine if the software is maintainable (i.e. it can be adapted to meet new requirements in future). On the basis of the results of the review, the customer will either make milestone payments, or will commence legal proceedings to recover liquidated damages from your employer. The independent reviewer is a scrupulously honest and cynical bastard, with tremendous experience with large software systems, and also has a reputation for recommending that the customer reject about half of the systems that he assesses. You are required, as the advocate of using global state, to justify a claim that the system works as intended and will be maintainable. How would you go about that?
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. string varibles??
    By Labmouse in forum C++ Programming
    Replies: 2
    Last Post: 08-23-2007, 08:16 AM
  2. Declaring Varibles
    By lbrault in forum C++ Programming
    Replies: 6
    Last Post: 02-05-2003, 12:23 PM
  3. extern varibles
    By manwhoonlyeats in forum C Programming
    Replies: 5
    Last Post: 12-18-2002, 12:43 AM
  4. C Functions and varibles
    By mart_man00 in forum C Programming
    Replies: 13
    Last Post: 08-01-2002, 01:11 PM
  5. varibles
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 06-24-2002, 10:15 AM