变量的作用域

This commit is contained in:
flykhan 2023-06-15 15:15:50 +08:00
parent 48b67927c5
commit b1c38f25c4
2 changed files with 45 additions and 0 deletions

24
day4/d5.cpp Normal file
View File

@ -0,0 +1,24 @@
#include <iostream>
using namespace std;
int n; // 全局变量
// 定义函数
void test1()
{
n = 100;
}
int main()
{
test1(); // 调用 test1 函数
cout << "global n = " << n << endl;
{
int m;
cout << "local m = " << m << endl;
}
// 跳出局部区域 m 变量则不能访问
// cout << "m = " << m << endl;
return 0;
}

21
day4/d7.cpp Normal file
View File

@ -0,0 +1,21 @@
#include <iostream>
using namespace std;
// 声明变量 n 为 int 类型
extern int n;
// void 表示无返回数据
void test2()
{
// 假如存在一个全局变量 n
n += 20; // n=n+20; += 符合赋值运算符
cout << "int test2 function n = " << n << endl;
}
int n = 10;
int main()
{
test2();
cout << "int main function n = " << n << endl;
return 0;
}