5

代码 :

int a = 33;
int main()
{
  int a = 40; // local variables always win when there is a conflict between local and global.
  // Here how can i access global variable 'a' having value '33'.
}

如果你问:为什么有人想做上面的事情?为什么是 [a-zA-Z]* ?

我的回答是:只要知道'有可能这样做'。

谢谢。

4

3 回答 3

15

这个老把戏怎么样:

int main()
{
    int a = 40; // local variables always win when there is a conflict between local and global.

    {
        extern int a;
        printf("%d\n", a);
    }
}
于 2013-03-10T20:06:37.590 回答
11
int a = 33;
int main()
{
  int a = 40;
  int b;
  {
    extern int a;
    b = a;
  }
  /* now b contains the value of the global a */
}

a如果它static与文件范围有关,则会遇到一个更难的问题,但这也是可以解决的:

static int a = 33;
static int *get_a() { return &a; }
int main()
{
  int a = 40;
  int b = *get_a();
  /* now b contains the value of the global a */
}
于 2013-03-10T20:07:12.333 回答
4

它是 C++,我忽略了C标签,抱歉!

int a = 100;

int main()
{
    int a = 20;

    int x = a; // Local, x is 20

    int y = ::a; // Global, y is 100

    return 0;
}
于 2013-03-10T20:41:25.053 回答