【发布时间】:2017-06-19 11:01:19
【问题描述】:
我有这段代码:
#include <stdio.h>
// global variable definition
int x = 0;
void access_global(){
cout << "ACCESSING FROM access_global()" << endl;
if (x > 0){
cout << "LOCAL VARIABLE" << endl;
cout << x << endl;
}
else{
cout << "GLOBAL VARIABLE" << endl;
cout << x << endl;
}
}
int main(int, char*[])
{
// declare new variable in given scope with same name as global variable
int x = 1;
cout << "ACCESSING FROM main()" << endl;
if (x > 0){
cout << "LOCAL VARIABLE" << endl;
cout << x << endl;
}
else{
cout << "GLOBAL VARIABLE" << endl;
cout << x << endl;
}
access_global();
return 0;
}
它输出:
ACCESSING FROM main()
LOCAL VARIABLE
1
ACCESSING FROM access_global()
GLOBAL VARIABLE
0
为什么access_global() 不访问x 范围内的main()?
是否可以修改access_global() 函数,使其显示main() 范围内的主要x 变量,如果未定义,则显示在main() 之外定义的变量?如果不可能,您能解释一下原因吗?谢谢
【问题讨论】:
-
请澄清为什么我被否决了。谢谢
-
函数内部的局部变量或 if/else、循环不能从外部访问。它不像命名空间。
-
@Raindrop7 “它不像命名空间”是什么意思。您可以发布一些链接或在答案中澄清这一点吗?
标签: c++ c function scope global-variables