提问人:M_G_0xFF 提问时间:11/10/2023 最后编辑:M_G_0xFF 更新时间:11/10/2023 访问量:72
为什么函数使用全局变量,当我们有 2 个具有相同标识符的变量时跳过局部变量
Why function uses the global variable and skip the local one when we have 2 variables with the same identifier
问:
据我所知,当我使用一个函数时,它会创建一个嵌套在主堆栈帧中的堆栈帧,并且根据这一点,假设当一个变量被引用并且它没有在函数作用域中声明时,该函数会逐渐进入更大的作用域,所以这里它应该在跳转到全局之前进入局部作用域, 还是我误解了?
#include <stdio.h>
#include <windows.h>
int X = 2;
void Scope(void);
int main()
{
int X = 3;
Scope();
return 0;
}
void Scope(void)
{
printf("Entering X = %d\n" ,X);
printf("Exiting X = %d\n" , X*X);
}
答:
0赞
0___________
11/10/2023
#1
在您的示例中,main 在函数中不可见,因为 Scope 是一个单独的函数,它看不到来自其他函数的自动存储持续时间变量。它只能看到“全局”或编译单元静态存储持续时间变量。X
Scope
评论
X
main()
Scope()
X = 2;
int
X
Scope()