【问题标题】:How to access global variable when there is a local and global conflict [duplicate]发生局部和全局冲突时如何访问全局变量[重复]
【发布时间】:2013-02-25 22:34:14
【问题描述】:

代码:

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

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

谢谢。

【问题讨论】:

  • 这确实是个好问题,但[a-zA-Z]* 是什么?
  • 表示任何以“为什么”开头并以“?”结尾的问题例如为什么要在这里访问全局?或者为什么等等等等?
  • @VishalD 得到它阅读我的答案也得到更多方法:)

标签: c global-variables


【解决方案1】:

这个老把戏怎么样:

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 击败我 30 秒。
  • +1:不错的把戏..不知道。
  • @R.. 公平地说,我想我是很久以前在你的一篇旧帖子中第一次看到它的。
  • @cnicutar 与 extern 关键字 相比,您何时更愿意通过指针访问? 我认为它也适用于全局静态变量。正确 ?
  • @GrijeshChauhan 我认为最好首先避免名称冲突,方法是保护性地命名您的代码导出的对象和函数(即所有不是static)。另一方面,如果您已经有了指针,则无需使用此技巧。
【解决方案2】:
int a = 33;
int main()
{
  int a = 40;
  int b;
  {
    extern int a;
    b = a;
  }
  /* now b contains the value of the global a */
}

如果static 具有文件范围,则更难的问题是获取a,但这也是可以解决的:

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 */
}

【讨论】:

  • 为什么不直接做int b = a; int a = 40;?或者,编译器可能会在这种情况下重新排序这些行......
  • 确实可以。
【解决方案3】:

它是 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-28
    • 2015-12-02
    • 2018-10-28
    • 2015-08-19
    • 2016-12-27
    相关资源
    最近更新 更多