in reply to Re: Re: Help - I'm a C programmer
in thread Help - I'm a C programmer

The thing about global variables is not the way they work; it's generally the problem with namespace collisions.

There are times when you do need something similar to a global variable functionality; in languages where namespace collisions can be easily avoided, such as C++, Java, Perl, or the like, you should never define a global variable, instead creating one at an Object or Package scope. Unforunately, you can't do the same for C; the best you can do is create a special variable with a very descriptive name to act as a global, such that the chance for namespace collision is low. Even with something like errno, that ought to be stored away in some non-global area to prevent some third party code overwriting it unintentionally before you have a chance to use it.


Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain

Replies are listed 'Best First'.
Re (tilly) 4: Help - I'm a C programmer
by tilly (Archbishop) on Jun 18, 2001 at 19:29 UTC
    If you want to store away errno, you can.

    But if you want to do that then you probably wanted to use a variable other than errno.

    Remember that the purpose of errno ($! to Perl programmers) is to pass a very specific type of error information implicitly between code that otherwise knows little about each other. Having each library define its own little custom error reporting tool just results in turning error handling into such a mess that nobody will bother to do it.

    Now I agree with both telling beginning programmers the naive rule, and telling more experienced programmers the fact that it isn't always true. But for me the litmus test is simple. The question is, "Is this something that I want to have all of my code be aware of?" If I don't want to always be thinking of it, then it shouldn't be global. If I don't want to always be thinking of it within this package, then it shouldn't be a package global either.

    So as you see, I am not religious about saying, "NO GLOBALS". However I don't use very many of them...

Re: Re: Re: Re: Help - I'm a C programmer
by John M. Dlugosz (Monsignor) on Jun 18, 2001 at 05:14 UTC
    I use, for #define symbols that are horribly global, names based on UUID's (a.k.a. GUID's). That cannot match anyone else's generated UUID, and is quite unlikely to match a random string of hex digits that someone just pulled out of the air or generated with some other algorithm.

    —John