• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 234
  • Last Modified:

accessing global variable in c.

hello.
in c++ we have :: operator to acess global variable ( if we have a local variable with the same name as that of global variable).
BUT how does we access such a global variable in c?
e.g


int x;
main()
{
       int x;
      :
      :

}

how do i access global x in main()
0
soodsandeep
Asked:
soodsandeep
1 Solution
 
SilkySharkCommented:
You can't with a 'normal' language construct.
You can by using pointers that point to the original variable but that is not really any point.
0
 
sunnycoderCommented:
SilkyShark is right, you can't.

There are a number of work arounds though ... pointers, as already suggested, is one of them
Another would be to write a function which simply returns the value of the global variable

int FetchGlobalVar ()
{
  return (GlovalVar);
}

These and more ways + discussions on this very topic are here
http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_20722542.html
0
 
stefan73Commented:
Hi soodsandeep,
You shouldn't do this, anyway. It's not good programming style. Since C lacks C++'s namespaces, you'd normally prefix globals, or store them in a global structure - it's less pollution of the global namespace.

Cheers!

Stefan
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now