每一次incrementandprint称,一个变量值是创造和分配价值的1。incrementandprint增量值为2,然后打印的值为2。当incrementandprint结束运行时,变量超出范围并被销毁。因此,该程序的输出:
2
2
2
现在考虑这个计划的固定范围的版本。这和上面的程序之间唯一的区别是,我们已经改变了局部变量的值自动定期使用static关键字。
固定的持续时间(使用static关键字):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
void IncrementAndPrint()
{
using namespace std;
static int s_nValue = 1; // fixed duration
++s_nValue;
cout << s_nValue << endl;
} // s_nValue is not destroyed here, but becomes inaccessible
int main()
{
IncrementAndPrint();
IncrementAndPrint();
IncrementAndPrint();
}
在这个程序中,因为s_nvalue已被声明为静态的,s_nvalue仅仅是创建和初始化(1)一次。当它超出范围,它不被破坏。每一次的函数incrementandprint()称,s_nvalue的价值是无论我们把它之前。因此,该程序的输出:
2
3
4
使用匈牙利表示法,它是常见的固定持续时间的变量前缀“s_”。一些程序员使用“S”(我们不喜欢因为这封信被更好的用于结构)或“c_”(我们不喜欢因为它不是为记)。
一个固定的时间局部变量最常见的用途是唯一标识符发生器。在处理程序中的类似的对象的数量很大,它分配给每个一一独特的ID号,所以他们可以识别往往是有益的。这是做的一个固定的时间局部变量很容易: