C/C++中static关键字的使用
When modifying a variable, the static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal
linkage (its name is not visible from outside the file in which it is declared).
例子:
test.h:
static int sVar2;
int Test1()
{
static int sVar1 = 10;
sVar1*=2;
return sVar1;
}
test.cpp
#include "stdio.h"
#include "test.h"
// sVar2 = 10; // 这里调用会编译出错 ??◎疑问1
int main(int argc, char* argv[])
{
sVar2 = 10; // 在VC++中,sVar2的确没有出现在WorkSpace->ClassView->Globals的变量表中,但却在main中
// 可以调用。◎疑问2??
printf("Test1()=%d\n", Test1());
printf("Test1()=%d\n", Test1());
printf("Test1()=%d\n", Test1());
printf("sVar2= %d\n", sVar2);
return 0;
}
VC执行结果:
Test1()=20
Test1()=40
Test1()=80
sVar2= 10
疑问1:sVar2为什么不能在test.cpp中main()之外不能使用
疑问2:MSDN说static修饰的变量不能在其文件之外可见,可在test.cpp中main()里可以使用,这又是为什么?
疑问3:用static修饰的函数到底有什么特点?