#include <stdio.h>
int* f() {//下面变量n在函数结束后会被系统回收所以我们需要用到static
static int n = 100;//static让n不会被回收
n++;//这里可以看得出来每次函数f被调用后变量n都在自增
return &n;
}
int main() {
int *f1 = f();//调用一次函数通过指针指向n的元素一次
printf("%d\n", *f1);
f();//第二次
printf("%d\n", *f1);
f();//第三次
printf("%d\n", *f1);
return 0;
}
通过打印,我们得知每次调用函数n的值被获取后可以自增,说明static让n的值不被系统刷新
#include <stdio.h>
int* f() {//下面变量n在函数结束后会被系统回收
int n = 100;
n++;//这里可以看得出来每次函数f被调用后变量n不会自增
return &n;
}
int main() {
int *f1 = f();//调用一次函数通过指针指向n的元素一次
printf("%d\n", *f1);
f();//第二次
printf("%d\n", *f1);
f();//第三次
printf("%d\n", *f1);
return 0;
}
上面我们没有使用static,每次调用都重新被刷新再调用第二次。