467,911 Members | 1,504 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,911 developers. It's quick & easy.

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

Dheeraj Joshi
Expert 1GB
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

Expand|Select|Wrap|Line Numbers
  1. #include<something.h>
  2. int countVal = 100;
  3. /*
  4. Some stuff
  5. */
  6.  
  7. void myFunction()
  8. {
  9. int countVal;
  10. }
  11.  
So here in function myFunction i have a local variable same as global variable.
So inside the function can i still use global variable(countVal). If yes how.?

Regards
Dheeraj Joshi
Jan 13 '10 #1
  • viewed: 3350
Share:
4 Replies
Airslash
100+
nameless namespace.

preceed your global variable with :: when calling it.

so use this code:

Expand|Select|Wrap|Line Numbers
  1. #include<something.h>
  2. int countVal = 100;
  3. /*
  4. Some stuff
  5. */
  6.  
  7. void myFunction()
  8. {
  9. int countVal;
  10. // to use global variable
  11. ::countVal
  12. // to use local variable
  13. countVal
  14. }
  15.  
Jan 13 '10 #2
Banfa
Expert Mod 8TB
Note the Scope Resolution Operator :: only exists in C++ so this technique doesn't work in C where you are basically stuffed.
Jan 13 '10 #3
Expert 2GB
You can be tricky like this:
Expand|Select|Wrap|Line Numbers
  1. int countVal = 100; 
  2. static int * const prwGlobalCountVal = &countVal;
  3. static const int * const proGlobalCountVal = &countVal;
  4. ...
  5. void myFunction() 
  6.    int countVal; 
  7.    // for read/write access to global variable 
  8.    ... *prwGlobalCountVal ...
  9.    // for read-only access to global variable 
  10.    ... *proGlobalCountVal ...
  11.    // to use local variable 
  12.    ... countVal ...
  13. }
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.
Jan 13 '10 #4
Dheeraj Joshi
Expert 1GB
Ok... Thanks for the reply...

Regards
Dheeraj Joshi
Jan 15 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

8 posts views Thread by David Hitillambeau | last post: by
2 posts views Thread by Thomas Matthews | last post: by
2 posts views Thread by C Gillespie | last post: by
7 posts views Thread by Michael | last post: by
9 posts views Thread by Shilpa | last post: by
4 posts views Thread by RgeeK | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.