存储期是变量在内存中的存储期限,存储器分为动态存储期和静态存储期。
局部变量定义时不赋初值,那么其初值是不确定的:
#include<bits/stdc++.h>using namespace std;/**** 局部变量定义时不赋初值,那么其初值是不确定的** */int main() {int a[10]; // 定义时未赋初值,其初值不确定for(int i = 0; i < 10; i++) {printf("%d ", a[i]);}puts("");return 0;}
2073290835 -2 6422280 1988918685 4200912 6422356 4201003 4200912 17765480 0
局部静态变量,初始值只赋值一次,函数调用消失后保留原值,下次函数调用时保留上次调用函数结束时的值:
#include<bits/stdc++.h>using namespace std;/*** 局部静态变量,只赋值一次* */int f() {static int a = 0; // 局部静态变量a++;return a;}int main() {for(int i = 0; i < 3; i++) {printf("%d%c", f(), " \n"[i==2]);}return 0;}
1 2 3
extern 扩展全局变量作用域:
在单个文件中扩展
#include<bits/stdc++.h>using namespace std;/*** extern 对变量做提前引用声明,扩展在程序中的作用域* */int my_max(int x, int y) {return x > y ? x : y;}int main() {extern int a, b; // 提前声明变量cout<<my_max(a, b)<<endl;return 0;}int a = 15, b = -7;
在多个文件中扩展:
#include<bits/stdc++.h>#include "4.2.cpp"using namespace std;extern int a, b; // 需要使用 extern 扩展作用域,否则就是重定义int main() {printf("a=%d b=%d\n", a, b);return 0;}
其中另一个文件中的内容
int a = 3, b = 4;
