1
    #include <stdio.h>

/* global variable declaration */
int g = 20;

int main ()
{
  /* local variable declaration */
  int g = 10;

  printf ("value of g = %d  %d\n",  g,::g);

  return 0;
}

When i am trying to run this program. It is throwing error main.c:11:39: error: expected expression before ':' token printf ("value of g = %d %d\n", g,::g);. But if it is written in C++, it works fine.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
Amit Shakya
  • 1,396
  • 12
  • 27

1 Answers1

3

No, that's a C++ feature. In C, declaring a variable in an inner scope will hide the one in the outer scope.

If you must do it, you can use pointers to get at the outer scope but it's a bit of a kludge and not something I'd recommend:

#include <stdio.h>
int g = 20;
int main () {
  int *pGlobalG = &g;
  int g = 10;
  printf ("value of g = %d %d\n", g, *pGlobalG);
  return 0;
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • You can also refer to the file-scope variable as `extern g` even redeclaring in an inner scope. ie. adding `{ extern int g; printf("value of global g = %d\n", g); }` just before the return in the above program. ... oh. duh. That's already in the linked answer. :) – luser droog Jan 18 '14 at 08:49
  • 1
    Why would anybody want to shadow an variable and then use a pointer to get back at it? that screams for sideeffects when maintaining the code. Variable names are free anyway. I would like to see a real world example where one "must" do it. – Devolus Jan 18 '14 at 09:09
  • Devolus, I can't actually think of a real reason where I would need to do it, which is why I couldn't recommend it. OP may have a reason, however bizarre :-) – paxdiablo Jan 18 '14 at 23:11