这个简单的问题很少有人能回答完全。在C语言中,关键字static有三个明显的作用:
1在函数体,一个被声明为静态的变量在这一函数被调用过程中维持其值不变。
2 在模块内(但在函数体外),一个被声明为静态的变量可以被模块内所用函数访问,但不能被模块外其它函数访问。它是一个本地的全局变量。
3在模块内,一个被声明为静态的函数只可被这一模块内的其它函数调用。那就是,这个函数被限制在声明它的模块的本地范围内使用。
大多数应试者能正确回答第一部分,一部分能正确回答第二部分,同是很少的人能懂得第三部分。这是一个应试者的严重的缺点,因为他显然不懂得本地化数据和代码范围的好处和重要性
int testStatic()
{
int x=1;
x++;
return x;
}
main()
{
int i;
for(i=0;i<5;i++)
printf("%d/n",testStatic());
getch();
}
==》2 2 2 2 2
int testStatic()
{
static int x=1;
x++;
return x;
}
main()
{
int i;
for(i=0;i<5;i++)
printf("%d/n",testStatic());
getch();
}
==》2 3 4 5 6
// Test_Static.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
//int testStatic()
//{
// int x=1;
// x++;
// return x;
//}
//void main()
//{
// int i;
// for(i=0;i<5;i++)
// printf("%d/n",testStatic());
// getch();
//}
//int testStatic()
//{
// static int x=1;
// x++;
// return x;
//}
//void main()
//{
// int i;
// for(i=0;i<5;i++)
// printf("%d/n",testStatic());
// getch();
// }
class A
{
//static int a=0;
public:
static int a;
A()
{
}
void outA()//error,it must be void outA()
{
cout<<"a is "<<a<<endl;
a++;
}
};
int A::a=1;//要在这里初始化模块的静态变更
void main()
{
A b;
b.outA();
A c;
c.outA();
}