当存在本地和全局冲突时如何访问全局变量

时间:2013-03-10 20:02:45

标签: c global-variables

代码:

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] *?

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

感谢。

3 个答案:

答案 0 :(得分:13)

这个老把戏怎么样:

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);
    }
}

答案 1 :(得分:8)

int a = 33;
int main()
{
  int a = 40;
  int b;
  {
    extern int a;
    b = a;
  }
  /* now b contains the value of the global a */
}

如果文件范围astatic,那么更难的问题是获得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 */ } ,但这也是可以解决的:

{{1}}

答案 2 :(得分: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;
}