C/C++日志20
当 static 用于局部变量时,它使该变量在函数调用之间保持其值,也就是说,静态局部变量只会在程序的第一次调用时初始化一次,之后每次调用函数时,静态局部变量都保持上次调用结束时的值。
- 作用域:静态局部变量的作用域仅限于其所在的函数内部。
- 生命周期:静态局部变量的生命周期从程序开始到程序结束,尽管它仅在函数内可见。
#include <iostream>
using namespace std;
void countCalls()
{
static int count = 0; // 静态局部变量
count++; // 每次调用时,count 的值都会增加
cout << "This function has been called " << count << " times." << endl;
}
int main()
{
countCalls();//This function has been called 1 times.
countCalls();//This function has been called 2 times.
countCalls();//This function has been called 3 times.
return 0;
}
当 static 用于全局变量时,它限制了该变量的作用域仅限于声明它的源文件。这意味着它不能被其他源文件访问。
- 作用域:静态全局变量的作用域仅限于当前源文件。
- 生命周期:静态全局变量的生命周期从程序开始到程序结束。
#include <iostream>
using namespace std;
static int globalVar = 10; // 静态全局变量
void display()
{
cout << "Global variable: " << globalVar << endl;
}
int main()
{
display();
// 外部文件无法访问 globalVar,因为它是静态的
return 0;
}
查看17道真题和解析
巨人网络公司福利 91人发布