Global Variables

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Matt

    Global Variables

    Greetings,
    What are people's thoughts on global variables in C++?
    Why are we taught not to use them in programming?
    Is it true that if you are running two copies of the C program one
    copy can overwrite another copies global variable?

    I know that you could overwrite a value in a global variable from a
    function, but you could also do that if you pass the variable in and
    then out again... so how is that any different?

    Can anyone shed light on these questions?
  • lilburne

    #2
    Re: Global Variables

    Matt wrote:
    [color=blue]
    > Greetings,
    > What are people's thoughts on global variables in C++?
    > Why are we taught not to use them in programming?
    > Is it true that if you are running two copies of the C program one
    > copy can overwrite another copies global variable?[/color]

    Not normally. Only if they arrange to share the same address
    space.
    [color=blue]
    > I know that you could overwrite a value in a global variable from a
    > function, but you could also do that if you pass the variable in and
    > then out again... so how is that any different?[/color]

    Global variables increase the data coupling of the program
    and thus its complexity, because the value can be changed
    from anywhere within the program.

    Comment

    • Michael Winter

      #3
      Re: Global Variables

      "Matt" wrote on 12/11/2003:
      [color=blue]
      > Greetings,
      > What are people's thoughts on global variables in C++?[/color]

      There's nothing wrong with global variables, but if possible, you
      should avoid using them. However, in certain situations they are
      necessary. A simple example is when passing a variable through 15
      function calls, but only the last function actually makes use of it.
      In this case, you're bulking up parameter lists, just to avoid a
      global. There are better examples, and hopefully someone else will
      give one...
      [color=blue]
      > Why are we taught not to use them in programming?[/color]

      Tracking down faults relating to globals is more difficult than one
      restricted to an object or a function. If you find that garbage gets
      put into that global, you'll have to watch every access between the
      last known good value (which might only be at initialisation) , to when
      you first see a problem (and that might not actually be the first
      occurence of a fault).
      [color=blue]
      > Is it true that if you are running two copies of the C program one
      > copy can overwrite another copies global variable?[/color]

      No. Global variables are not shared with other programs, full-stop.
      It doesn't matter if their the same executable or a different one, a
      process' address space is its own. Exceptions can be introduced when
      you start with debugging, and such, but that's not what you're asking
      (and beyond the scope of this discussion).
      [color=blue]
      > I know that you could overwrite a value in a global variable from a
      > function, but you could also do that if you pass the variable in and
      > then out again... so how is that any different?[/color]

      When you say: "pass the variable in and then out again," do you mean
      passing a local variable to a function? If so, then what you say is
      not necessarily true:

      If you pass by value, a copy of the variable is made, so any changes
      are not reflected in the original variable.
      If you pass by reference, changes are reflected, but you could prevent
      that by specifying that the variable is 'const'.
      If you pass the address with a pointer, again, changes are reflected
      but like references, the memory that the pointer addresses can be
      marked 'const'.
      [color=blue]
      > Can anyone shed light on these questions?[/color]

      I hope I did.

      Mike

      --
      Michael Winter
      M.Winter@[no-spam]blueyonder.co.u k (remove [no-spam] to reply)


      Comment

      • Stephane Richard

        #4
        Re: Global Variables

        Here's a derived question from your reply :-).

        Is there a full proof way to assure than no two copies of the same C / C++
        program would ever share the same address space?

        Is that the behavior by default and you have to code to share the address
        spaec amongst instances of the program? or is it the other way around and
        you have to code to assure that the don't share the same address space?

        Stéphane Richard


        "lilburne" <lilburne@godzi lla.net> wrote in message
        news:boudi3$1ft 8jo$1@ID-203936.news.uni-berlin.de...[color=blue]
        > Matt wrote:
        >[color=green]
        > > Greetings,
        > > What are people's thoughts on global variables in C++?
        > > Why are we taught not to use them in programming?
        > > Is it true that if you are running two copies of the C program one
        > > copy can overwrite another copies global variable?[/color]
        >
        > Not normally. Only if they arrange to share the same address
        > space.
        >[color=green]
        > > I know that you could overwrite a value in a global variable from a
        > > function, but you could also do that if you pass the variable in and
        > > then out again... so how is that any different?[/color]
        >
        > Global variables increase the data coupling of the program
        > and thus its complexity, because the value can be changed
        > from anywhere within the program.
        >[/color]


        Comment

        • lilburne

          #5
          Re: Global Variables

          Stephane Richard wrote:
          [color=blue]
          >
          > Is that the behavior by default and you have to code to share the address
          > spaec amongst instances of the program? or is it the other way around and
          > you have to code to assure that the don't share the same address space?
          >[/color]

          You have to have OS support in order to do it via shared
          memory, memory mapped ports, etc, you have to very specific
          about it. In general one process will not be able to access
          memory owned by another process, at least not on common OS.
          Constants may reside in the program's 'text' segment and
          could be shared if multiple instances of a program share the
          same text.

          I wouldn't worry about it. You'll probably never encounter
          such things.

          Comment

          • Roger Leigh

            #6
            Re: Global Variables

            matth@chilitech .net (Matt) writes:
            [color=blue]
            > Greetings,
            > What are people's thoughts on global variables in C++?
            > Why are we taught not to use them in programming?[/color]

            Global variables are generally very bad, but occasionally useful where
            you want global state. They are used by both the C and C++ standard
            libraries for some things e.g. global locale, std::cin, std::cout
            etc. are also global objects, albeit within a namespace.

            As an example of why it's bad, part of my job involves maintaining
            code written in an old DOS-based 4GL database language. It has no
            concept of classes or even local variables. Every variable is global.
            The result is that each program has around 200 (a few have over 500!)
            variable definitions right at the top. This is bad because it's
            nearly impossible to keep track of what code uses each variable. Some
            hard-to-debug problems are because a variable can be modified in many
            places, or used for different purposes.

            I'm currently slowly re-writing in C++. For the parts I've rewritten,
            the code size has been reduced by a factor of about 10, and I'm
            already getting better performance and reliability even though I'm not
            finished doing the prototype yet. Another benefit is ease of
            maintainence: it took me two weeks solid work to make a trivial change
            to the 4GL code, due to the impossible to predict interactions that
            made even the smallest change problematic. The same change to the C++
            code should take about 20 *minutes*.

            C++ or even C are a breath of fresh air after that. The 4GL dogs'
            breakfast really makes you appreciate what benefits we derive from
            functions and classes. Encapsulating the logic in functions and
            classes makes for a much more robust and predictable program. The
            code is a joy to write, and looks beautiful.
            [color=blue]
            > Is it true that if you are running two copies of the C program one
            > copy can overwrite another copies global variable?[/color]

            No, at least for the operating systems I've used (various UNIX,
            Windows).
            [color=blue]
            > I know that you could overwrite a value in a global variable from a
            > function, but you could also do that if you pass the variable in and
            > then out again... so how is that any different?[/color]

            I'm not sure exactly what you mean here. Could you clarify the
            question?


            --
            Roger Leigh

            Printing on GNU/Linux? http://gimp-print.sourceforge.net/
            GPG Public Key: 0x25BFB848. Please sign and encrypt your mail.

            Comment

            • Matt

              #7
              Re: Global Variables

              Roger Leigh <${roger}@inval id.whinlatter.u klinux.net.inva lid> wrote in message news:<87n0b0gl7 h.fsf@wrynose.w hinlatter.uklin ux.net>...[color=blue]
              > matth@chilitech .net (Matt) writes:
              >[color=green]
              > > Greetings,
              > > What are people's thoughts on global variables in C++?
              > > Why are we taught not to use them in programming?[/color]
              >
              > Global variables are generally very bad, but occasionally useful where
              > you want global state. They are used by both the C and C++ standard
              > libraries for some things e.g. global locale, std::cin, std::cout
              > etc. are also global objects, albeit within a namespace.
              >
              > As an example of why it's bad, part of my job involves maintaining
              > code written in an old DOS-based 4GL database language. It has no
              > concept of classes or even local variables. Every variable is global.
              > The result is that each program has around 200 (a few have over 500!)
              > variable definitions right at the top. This is bad because it's
              > nearly impossible to keep track of what code uses each variable. Some
              > hard-to-debug problems are because a variable can be modified in many
              > places, or used for different purposes.
              >
              > I'm currently slowly re-writing in C++. For the parts I've rewritten,
              > the code size has been reduced by a factor of about 10, and I'm
              > already getting better performance and reliability even though I'm not
              > finished doing the prototype yet. Another benefit is ease of
              > maintainence: it took me two weeks solid work to make a trivial change
              > to the 4GL code, due to the impossible to predict interactions that
              > made even the smallest change problematic. The same change to the C++
              > code should take about 20 *minutes*.
              >
              > C++ or even C are a breath of fresh air after that. The 4GL dogs'
              > breakfast really makes you appreciate what benefits we derive from
              > functions and classes. Encapsulating the logic in functions and
              > classes makes for a much more robust and predictable program. The
              > code is a joy to write, and looks beautiful.
              >[color=green]
              > > Is it true that if you are running two copies of the C program one
              > > copy can overwrite another copies global variable?[/color]
              >
              > No, at least for the operating systems I've used (various UNIX,
              > Windows).
              >[color=green]
              > > I know that you could overwrite a value in a global variable from a
              > > function, but you could also do that if you pass the variable in and
              > > then out again... so how is that any different?[/color]
              >
              > I'm not sure exactly what you mean here. Could you clarify the
              > question?[/color]

              This did help somewhat.. what I mean is.. if the main reason for not
              using globals is to prevent accidental change.. then shouldn't I just
              be more careful when programming? Couldn't I do just as much damage
              passing a variable local into a function and then back out? The only
              difference with a global is I messed up coding... but isn't it ALSO
              just as bad coding practice to use the same variable locally that is
              defined in another function locally? I mean if you use the variable
              once you shouldn't use it again, so why not just define it globally
              and watch what you do??

              Comment

              • lilburne

                #8
                Re: Global Variables

                Matt wrote:
                [color=blue]
                > Roger Leigh <${roger}@inval id.whinlatter.u klinux.net.inva lid> wrote in message news:<87n0b0gl7 h.fsf@wrynose.w hinlatter.uklin ux.net>...
                >[color=green][color=darkred]
                >>>I know that you could overwrite a value in a global variable from a
                >>>function, but you could also do that if you pass the variable in and
                >>>then out again... so how is that any different?[/color]
                >>
                >>I'm not sure exactly what you mean here. Could you clarify the
                >>question?[/color]
                >
                >
                > This did help somewhat.. what I mean is.. if the main reason for not
                > using globals is to prevent accidental change.. then shouldn't I just
                > be more careful when programming? Couldn't I do just as much damage
                > passing a variable local into a function and then back out? The only
                > difference with a global is I messed up coding... but isn't it ALSO
                > just as bad coding practice to use the same variable locally that is
                > defined in another function locally? I mean if you use the variable
                > once you shouldn't use it again, so why not just define it globally
                > and watch what you do??[/color]

                By default C++ uses call by value not call by reference,
                unless you specify that a parameter is a non-const
                reference, or pointer, another function cannot modify the
                value of any variable passed to it.

                Comment

                • Karl Heinz Buchegger

                  #9
                  Re: Global Variables



                  Matt wrote:[color=blue]
                  >
                  > This did help somewhat.. what I mean is.. if the main reason for not
                  > using globals is to prevent accidental change.. then shouldn't I just
                  > be more careful when programming?[/color]

                  Lot's of people thought this and all of them came to the same conclusion
                  eventually:
                  No. Simply beeing careful doesn't help.

                  The reason is that programs very quickly cross a 'critical mass'. Once
                  this critical mass is crossed, the complexity raises that fast, that
                  it is extremely hard or impossible to recognize all the details.

                  By using local variables you draw a border. The border limits the scope
                  of that variable. It is as if you were saying: Your influence region is
                  up to here but no further.
                  [color=blue]
                  > Couldn't I do just as much damage
                  > passing a variable local into a function and then back out?[/color]

                  No. Cause it you pass something to a function you want to tell the function
                  something: use this value or calculate and place the result here.
                  You are using a defined interface and that's ok.

                  It is like a house: if you don't make any window or doors in your house,
                  then you don't need to worry of getting robbed. But what good is a house
                  without a door and/or windows? So you need to lower the security a little
                  bit in order to make it useful. But this does not mean that you want to
                  build your house without walls :-)
                  [color=blue]
                  > The only
                  > difference with a global is I messed up coding...[/color]

                  Not really.
                  [color=blue]
                  > but isn't it ALSO
                  > just as bad coding practice to use the same variable locally that is
                  > defined in another function locally?[/color]

                  No, why should it?
                  Those 2 variables have nothing in common. They just happen to have
                  the same name, but this isn't a problem, they are still independent of
                  each other. If you are working on one function, then you are interested in
                  the details of that function. If there is a local variable called 'count', fine.
                  Then you switch and are working on another function. There is also a variable called
                  'count', but since you don't use globals, you know that this is a completely
                  different variable then the one you previously used in another function.
                  So you also know (since both are global), that you can change each count
                  without affecting the operation of the other function. You simply don't care
                  any longer, that there is another function which uses a local variable 'count'.

                  [color=blue]
                  > I mean if you use the variable
                  > once you shouldn't use it again,[/color]

                  That would be hard to do in real world programs. The system my team is working
                  on consists of roughly 1 million lines of code, there are at least 60000 up to
                  100000 (I estimated this numbers, since nobody knows exactly) variables and you
                  tell me that I shouldn't use a variable called 'count' in more then one function?
                  If it is a counter and I use it as a counter I will call it 'count' and not worry
                  about all the other 5000 counter which are used throughout the whole program.
                  [color=blue]
                  > so why not just define it globally
                  > and watch what you do??[/color]

                  Because you can't watch them. At least not when you are writing serious programs
                  with sizes greater then 50 lines of code.

                  --
                  Karl Heinz Buchegger
                  kbuchegg@gascad .at

                  Comment

                  • Karl Heinz Buchegger

                    #10
                    Re: Global Variables



                    Karl Heinz Buchegger wrote:[color=blue]
                    >[/color]
                    [color=blue]
                    > No, why should it?
                    > Those 2 variables have nothing in common. They just happen to have
                    > the same name, but this isn't a problem, they are still independent of
                    > each other. If you are working on one function, then you are interested in
                    > the details of that function. If there is a local variable called 'count', fine.
                    > Then you switch and are working on another function. There is also a variable called
                    > 'count', but since you don't use globals, you know that this is a completely
                    > different variable then the one you previously used in another function.
                    > So you also know (since both are global), that you can change each count[/color]

                    must obviously read: ... (since both are local), ...

                    --
                    Karl Heinz Buchegger
                    kbuchegg@gascad .at

                    Comment

                    • E. Robert Tisdale

                      #11
                      Re: Global Variables

                      Matt wrote:
                      [color=blue]
                      > What are people's thoughts on global variables in C++?[/color]

                      Global *variables* are bad.
                      Global *constants* are good.
                      [color=blue]
                      > Why are we taught not to use them in programming?
                      >
                      > Is it true that, if you are running two copies of the C program,
                      > one copy can overwrite another copy's global variable?[/color]

                      No.
                      [color=blue]
                      > I know that
                      > you could overwrite a value in a global variable from a function
                      > but you could also do that
                      > if you pass the variable in and then out again...[/color]

                      You shouldn't do that either.
                      [color=blue]
                      > so how is that any different?
                      > Can anyone shed light on these questions?[/color]

                      You should try to avoid using variables.
                      They only make your code harder for other programmers
                      to read, understand and maintain.
                      You will appreciate that when you go back
                      to modify code that you haven't looked at for six months --
                      you *will* be that other programmer.

                      Use constants whenever possible.
                      You don't need *any* variables to write useful programs.
                      Place a 'const' qualifier if front of every variable definition
                      and allow the compiler to *force* you to change it back into a variable.

                      Don't write functions to pass pointers or references to variables.
                      Pass by value, const pointer or const reference
                      and return an object by value instead.
                      Consider passing a pointer or a reference
                      *only* for "in-place" operations such as operations
                      on the elements of a *container* object
                      like a long list or a large array.

                      Global constants are good.
                      Old C programmers used C preprocessor macros to define constants
                      in header files which could be included in every translation unit.
                      These macros have become obsolete with the introduction
                      of the 'const' qualifier.

                      Global constants, on the other hand, break modularity.
                      Global constants make the code harder to maintain
                      because the programmers must consider the impact
                      of any change of a global variable on every other function
                      called by the program and, unless they are the original author,
                      they will be obliged to inspect, analyse and understand
                      every other function that references the global variable.
                      Global variables make functions harder to reuse
                      in other programs because they depend upon other functions
                      that reference and modify the global
                      which may have nothing to do with the new program
                      or that conflict with the new program.

                      Global variables are *never* necessary.
                      They may appear to be convenient at first
                      but they eventually cause problems
                      which lead new programmers to regret every considering using them.




                      Comment

                      Working...