Accessing the global variable inside a function when we have a variable of same name

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    Accessing the global variable inside a function when we have a variable of same name

    Hi, I was wondering is there any technique available, so we can access the global variable inside a function if we have a local variable inside the function with the same name as global variable.

    Example

    Code:
    #include<something.h>
    int countVal = 100;
    /*
    Some stuff
    */
    
    void myFunction()
    {
    int countVal;
    }
    So here in function myFunction i have a local variable same as global variable.
    So inside the function can i still use global variable(countV al). If yes how.?

    Regards
    Dheeraj Joshi
  • Airslash
    New Member
    • Nov 2007
    • 221

    #2
    nameless namespace.

    preceed your global variable with :: when calling it.

    so use this code:

    Code:
    #include<something.h>
    int countVal = 100;
    /*
    Some stuff
    */
     
    void myFunction()
    {
    int countVal;
    // to use global variable
    ::countVal
    // to use local variable
    countVal
    }

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Note the Scope Resolution Operator :: only exists in C++ so this technique doesn't work in C where you are basically stuffed.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        You can be tricky like this:
        Code:
        int countVal = 100; 
        static int * const prwGlobalCountVal = &countVal;
        static const int * const proGlobalCountVal = &countVal;
        ...
        void myFunction() 
        { 
           int countVal; 
           // for read/write access to global variable 
           ... *prwGlobalCountVal ...
           // for read-only access to global variable 
           ... *proGlobalCountVal ...
           // to use local variable 
           ... countVal ...
        }
        But this is a good way to outsmart yourself. Much better to change the name of the local variable so there is no collision.

        Notice that this trick creates one or two aliases of the global variable. Therefore, you must make a point of not associating the restrict type qualifier with the global variable.

        A good lint will warn you if a local name overrides a wider-scope name.

        Comment

        • Dheeraj Joshi
          Recognized Expert Top Contributor
          • Jul 2009
          • 1129

          #5
          Ok... Thanks for the reply...

          Regards
          Dheeraj Joshi

          Comment

          Working...