代码:
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]*?
我的答案是:只是想知道“这是可能的”。
谢谢。
代码:
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'.
}
这个古老的技巧怎么样?
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);
}
}
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
的变量在文件作用域内,如何获取它,但这也是可以解决的:
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;
?或者说,编译器会在这种情况下重新排序代码吗? - ad absurdum这是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;
}
[a-zA-Z]*
是什么意思? - Grijesh Chauhan