Announcement

Collapse
No announcement yet.

Global Variables Question

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Global Variables Question

    What are the disadvantages to using global variables in a
    program? One application I am working on now would benefit
    from a large amount of global variables, however, if there is
    some disadvantage to doing that I can remove them (better now
    than when I'm done...!)


    ------------------

  • #2
    No disadvantages. Some people hate global variables, I'm addicted to them.
    Have been known to use up hundreds even in just a tiny little program.
    Just remember to give them names that relate to what they are used for
    and be careful they aren't used/changed in wrong place.


    ------------------

    Comment


    • #3
      I will assume that this is beyond the scope of your project, but you should be aware that if your app uses multiple threads, you'll need to use synchronization objects around all references to GLOBAL and STATIC variables that are used by the threads, in order to create thread-safe code.

      Search the BBS for "CriticalSection" for more info.

      OTOH, if you are not using threading, no problem with GLOBALs, just as Borje says.


      ------------------
      Lance
      PowerBASIC Support
      mailto:[email protected][email protected]</A>
      Lance
      mailto:[email protected]

      Comment


      • #4
        Ariel,

        I don't think there is anything "bad" about using global variables,
        it is just considered poor programming (according to my old
        computer science teacher), really my opinion is:

        Code:
        - Large amounts of global variables are hard to trace throughout the
          program
        - If you have many global variables your program will use much more
          memory then originally used if they were local to the sub/function.
          (sub/function variables) automatically destroy when the function/sub
          exits
        - The biggest mistake I make and it can be hard to trace is this:
        
        #COMPILE EXE
        
        GLOBAL gooble AS STRING
        
        SUB testme()
            LOCAL Gooble AS STRING
            Gooble = "TestMe"
        END SUB
        
        FUNCTION PBMAIN() AS LONG
            Gooble = "PBMAIN"
            TestMe
            MSGBOX Gooble
        END FUNCTION
        
        Whats the value of Gooble when it displays a messagebox?
        When I consider using Global Variables, I think of it this way.

        - Will I be sharing this value between multiply functions/sub
        - Is this method the best way? (usually it isn't)
        - Is this method hard to debug (Usually it isn't, unless tons of global variables)
        - Can I call an api/function/sub and get this value? If so, then why use a global variable


        If I do use global variables, I always use some type of hungarian notation to
        track my usuage like this:

        global glszBuffer as asciiz * %MAX_PATH

        first two char's = Scope
        Second two = String with Zero termination
        etc

        for local var's I drop the first two chars like this:

        local szBuffer as asciiz * %MAX_PATH

        so when your debugging it's easy to follow.

        I hope these comments has helped. Good luck


        ------------------
        -Greg
        -Greg
        [email protected]
        MCP,MCSA,MCSE,MCSD

        Comment


        • #5
          Nothing wrong at all with global variables, just remember to prefix them with a 'g' (ie: giAppSetting), so not to confuse them with other variables.
          Personally, I use a global UDT with app settings in nearly every program I write, PB, VB, C or other.

          When it comes to multiple window settings (ie: MDI children), see 'SetProp'

          Regards,

          ------------------
          Kev G Peel
          KGP Software, Bridgwater, UK.
          mailto:[email protected][email protected]</A>
          kgpsoftware.com | Slam DBMS | PrpT Control | Other Downloads | Contact Me

          Comment


          • #6
            Procedures which rely on GLOBAL variables are less portable/reuseable.

            MCM
            Michael Mattias
            Tal Systems (retired)
            Port Washington WI USA
            [email protected]
            http://www.talsystems.com

            Comment


            • #7
              The problem with global variables is that sometimes they are unavoidable.
              To help to develop good programming practices (what I mean is to keep from
              confusing myself), I try to use as few globals as possible. What I have
              found useful is to use Statics in my Main module, and a single global
              array of pointers to them. The individual members of the array are accessed
              using equates. Thus while developing my programs, I seem to be constantly
              changing the makeup of only one global array, rather than trying to keep
              track of multiple globals.
              ie. ' pointerID equates for dialog access to variables
              Code:
              %pID_hWnd            = 1   ' Main Window handle
              %pID_DisplayPrefs    = 2   ' Pointer to UDT for User Display preferences
              %pID_PrefFileINIpath = 3   ' Pointer to a string with the Path for an INI file
              %pID_noPntrs         = 3   ' Number of pointers in the array
              and later, the declarations:
              Code:
              GLOBAL gPtrArray() AS DWORD
              DIM PtrArray(1:%pID_noPntrs)
              and then the assignments:
              Code:
              gPtrArray(%pID_PrefFileINIpath) = VARPTR(szPrefFileINIPath)
              regards,


              ------------------
              [email protected]c.ca
              :) IRC :)

              Comment


              • #8
                In QB, if a variable is highlighted, F1 will display what it is & where it is used. If it is an element of a UDT, the UDT info. is displayed. For functions/subs the definition is displayed. Any chance of this in the next PB versions?
                In the meantime, I'll cope using PBCodec! (Thanks Borje!)

                ------------------

                Comment


                • #9
                  If you use Hungarian notation, you wouldn't need any IDE
                  features like that

                  ------------------
                  -Greg

                  [This message has been edited by Gregery D Engle (edited October 10, 2001).]
                  -Greg
                  [email protected]
                  MCP,MCSA,MCSE,MCSD

                  Comment


                  • #10
                    Hungarious? Thats a new one! I always thought it was just termed "Hungarian".

                    ------------------
                    Lance
                    PowerBASIC Support
                    mailto:[email protected][email protected]</A>
                    Lance
                    mailto:[email protected]

                    Comment


                    • #11
                      Hungarious? Hungarian??!?

                      I apologize my lack of knowledge. What's that stuff?

                      ------------------
                      Rgds, Aldo

                      Comment


                      • #12
                        'Hungarian Notation' is a way of naming variables to easily tell between different variable types, for example...

                        Code:
                        Dim iVariable As Integer
                        Dim lVariable As Long
                        Dim sVariable As String
                        Dim gsVariable As Global String
                        And so on...

                        I don't know why its called 'Hungarian' though, possibly invented by a Hungarian person?

                        ------------------
                        Kev G Peel
                        KGP Software, Bridgwater, UK.
                        mailto:[email protected][email protected]</A>
                        kgpsoftware.com | Slam DBMS | PrpT Control | Other Downloads | Contact Me

                        Comment


                        • #13
                          From an old MS book here: "Hungarian notation was invented by Charles Simonyi,
                          a Microsoft employee of Hungarian extraction".

                          Think "invented" is a strong word in this context though. He may have been the
                          first to implement this kind of naming convention in programming, but similar
                          way has been used in mathematical world for ages.


                          ------------------

                          Comment


                          • #14
                            Lance,

                            Thanks for pointing out my grammical error

                            ------------------
                            -Greg
                            -Greg
                            [email protected]
                            MCP,MCSA,MCSE,MCSD

                            Comment


                            • #15
                              We all moke mistooks!

                              "Hungarious" is certainly a fresh term, and one that I could easily coin to describe some software companies business strategies...

                              ------------------
                              Lance
                              PowerBASIC Support
                              mailto:[email protected][email protected]</A>
                              Lance
                              mailto:[email protected]

                              Comment


                              • #16
                                Back to global variables..
                                Isn't there a speed aspect to it too?
                                Local variables have to be 'created' every time a sub or function is called.
                                Doesn't this take time? While global variables are always there for the
                                sub to use, they do not have to be created..
                                Kind regards
                                Eddy



                                ------------------
                                [email protected]
                                Eddy

                                Comment


                                • #17
                                  Isn't there a speed aspect to it too?
                                  Local variables have to be 'created' every time a sub or function is called.
                                  LOCAL variables have to be "initialized" each call, but not "created", as that is done at compilation time; the LOCAL variable's address is fixed relative to the stack at compile time.

                                  Speed? Well, I guess technically there is a performance "penalty" for this initialization, but relative to the overhead of the CALL itself, it is totally insignificant.

                                  MCM


                                  Michael Mattias
                                  Tal Systems (retired)
                                  Port Washington WI USA
                                  [email protected]
                                  http://www.talsystems.com

                                  Comment


                                  • #18
                                    Ariel,

                                    Its really a matter of scope, you make a variable GLOBAL if it must
                                    be available across different functions and subs. In my own case, I
                                    make handles global as I tend to write code that accesses windows
                                    and controls from many different places.

                                    LOCAL variable have other advantages, they are created at the start
                                    of a function and are destroyed at the end so you will never end up
                                    with the wrong value in the wrong place with locals. This means you
                                    can reuse variable names in functions safely.

                                    I don't have a prejedice for either, they both have there place and
                                    while there is some overlap between them, they are really different
                                    capacities. The ANTI global mentality comes from OOP(s) literature
                                    where GLOBAL is bad, you are too dumb to write a select case block
                                    and if you code end up bloated, it does not matter.

                                    Regards,

                                    [email protected]

                                    ------------------
                                    hutch at movsd dot com
                                    The MASM Forum

                                    www.masm32.com

                                    Comment


                                    • #19
                                      Scalar variables and array descriptors are stored on the stack frame, so the overhead to initialize those is pretty low. Unless you were calling a Sub/Function at a very high rate, the difference would be difficult to measure in a 1-off case.

                                      However, if you do need to call a Sub/Function at a high rate, then you probably need to review your code design and move the code from the Sub/Function and make it "in-line" where it was being called from.

                                      Duplicating a bunch of code a few places in an app will grow the app size, but the impact on performance can make it worthwhile if the code is executed hundred of thousands or even millions of times in rapid succession.

                                      Also, using traditional GOSUB/RETURN can offer similar advantages in terms of execution performance.

                                      However, this has to be all taken in context. If you are writing "applications" (ie, Invoicing programs, etc), then it is hardly worth being concerned with. If you are writing a high-performance Fast Fourier Transform processing library, you may prefer to use inline code or GOSUB/RETURN over Subs/Functions.

                                      Finally, the reality is that the code contained in the Subs/Functions will probably take longer to execute than the small fractions of a second you are trying to avoid (from the required Sub/Function set up overhead).

                                      As has been discussed on this BBS many many times, the actual processor being used to test "tight loop" code can make a big impact on "measured" or "perceived" performance.

                                      So, going back to the original question, I would say that whether or not to use Global variables will depend on the programmer, his/her affection for Globals, and whether Globals offer the most suitable solution from a total design perspective, rather than just because using a Global may shave 0.000000000001 seconds of a given Sub/Function call.

                                      ------------------
                                      Lance
                                      PowerBASIC Support
                                      mailto:[email protected][email protected]</A>
                                      Lance
                                      mailto:[email protected]

                                      Comment


                                      • #20
                                        Scalar variables and array descriptors are stored on the stack frame, so the overhead to initialize those is pretty
                                        low
                                        Time ago I found evidence (PBCC) that LOCAL dynamic numeric arrays are initialized to zeroes at each call,
                                        resulting in significant speed reduction if large arrays are involved (much like if there was a sort of hidden FOR-NEXT loop setting all elements = 0).
                                        When speed (but NOT the initial values) was a concern, I have solved this problem by making these arrays STATIC.
                                        Am I correct ?
                                        Regards



                                        ------------------
                                        Aldo Vitagliano
                                        mailto:[email protected][email protected]</A>
                                        Aldo Vitagliano
                                        alvitagl at unina it

                                        Comment

                                        Working...
                                        X