“变量的作用域”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第53行: | 第53行: | ||
int g_max = 100; | int g_max = 100; | ||
//相同作用域重复定义变量名编译不通过 | //相同作用域重复定义变量名编译不通过 | ||
+ | </syntaxhighlight><syntaxhighlight lang="c"> | ||
+ | #include<stdio.h> | ||
+ | |||
+ | int g_max = 10; | ||
+ | |||
+ | int main() | ||
+ | { | ||
+ | int a = 100; | ||
+ | int b = 200; | ||
+ | { | ||
+ | int a = 0; | ||
+ | } | ||
+ | b = a + 10; | ||
+ | printf("%d \n", b); | ||
+ | return 0; | ||
+ | } | ||
+ | </syntaxhighlight><syntaxhighlight lang="console"> | ||
+ | 110 | ||
</syntaxhighlight> | </syntaxhighlight> |
2022年10月28日 (五) 07:01的版本
https://www.bilibili.com/video/BV1vR4y1H7MY/?p=8
变量的作用域(可见性):每一个变量名都有一个作用域问题,即变量名在什么范围内有效。
- 全局变量:在函数外定义的变量。
- 局部变量:在函数中定义的变量。
- 程序块中的变量:在函数外部,在复合语句中定义的变量。
#include<stdio.h>
int g_sum = 100; //全局变量
int main()
{
float ft = 12.23f; //局部变量
int a = 10;
int g_sum = 0; //局部变量和全局变量同名
a = g_sum; //? 100,0
return 0;
}
int g_max = 10;
void fun()
{
int a = g_max;
int sum = 0;
}
int main()
{
int x = g_max;
int sum = 10;
{
int z = 10;
z = 100;
//z的作用域仅在块内
}
//x = z + sum; //编译不通过
return 0;
}
int g_max = 10;
int main()
{
int a = 100;
int b = 200;
return 0;
}
int g_max = 100;
//相同作用域重复定义变量名编译不通过
#include<stdio.h>
int g_max = 10;
int main()
{
int a = 100;
int b = 200;
{
int a = 0;
}
b = a + 10;
printf("%d \n", b);
return 0;
}
110