1、register:将变存储于寄存器中
{
register int i;
}
2、static:变量的生命周期是整个程序周期,修饰全局变量时,不允许外部文件对该变量进行访问。
#include <iostream>
using namespace std;
int test()
{
static int i = 0;
return (++i);
}
int main()
{
int i,loop = 5;
for(;loop > 0;loop--)
{
i = test();
cout << "i:" << i << endl;
}
return 0;
}
输出结果为:
i:1
i:2
i:3
i:4
i:5
--------------------------------
Process exited after 0.365 seconds with return value 0
请按任意键继续. . .
由此可知,在test函数中的局部变量i,并没有随着test函数的调用结束而被销毁。对比下面去掉“static”程序的输出:
#include <iostream>
using namespace std;
int test()
{
//static int i = 0;
int i = 0;
return (++i);
}
int main()
{
int i,loop = 5;
for(;loop > 0;loop--)
{
i = test();
cout << "i:" << i << endl;
}
return 0;
}
输出结果为:
i:1
i:1
i:1
i:1
i:1
--------------------------------
Process exited after 0.1632 seconds with return value 0
请按任意键继续. . .
3、extern :引用外部文件的全局变量或者函数