一、概念
1、静态局部变量:使用static限定符在代码块中定义的变量。
2、原理分析:在代码块中使用
static时,将导致局部变量的存储持续性为静态的。 这意味着虽然该变量只在该代码块中可用,但它在该代码块不处于活动 状态时仍然存在。因此在两次函数调用之间,静态局部变量的值将保持 不变。另外,如果初始化了静态局部变量,则程序 只在启动时进行一次初始化。以后再调用函数时,将不会像自动变量那 样再次被初始化。
一句话概括就是
函数中定义的static变量,只会初始化一次,函数结束,值还在。
3、使用场景
做一些需要传值并累加的函数功能
二、示例代码
#include <iostream>
using namespace std;
void intCount(int i);
int main()
{
cout << "main() \n";
intCount(5);
intCount(7);
intCount(8);
return 0;
}
void intCount(int i)
{
static int total = 0;
cout<<"intCount()函数中total="<<total<<endl;
int count = 0;
while (i > 0)
{
i--;
count++;
}
total += count;
cout << "count=" << count << ",,,total=" << total << endl;
}
程序运行结果:
intCount()函数中total=0
count=5,,,total=5
intCount()函数中total=5
count=7,,,total=12
intCount()函数中total=12
count=8,,,total=20
从结果中可以看到,intCount()函数中total的初始值并不是一直是0,随着total不断累加而发生改变