静态变量的类型关键字是static。 静态变量当然是属于静态存储方式,但是属于静态存储方式的量不一定就是静态变量, 例如外部变量虽属于静态存储方式,但不一定是静态变量,必须由 static加以定义后才能成为静态外部变量,或称静态全局变量。 对于自动变量,它属于动态存储方式。 但是也可以用static定义它为静态自动变量,或称静态局部变量,从而成为静态存储方式。 由此看来,一个变量可由static进行再说明,并改变其原有的存储方式
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include<stdio.h> int fun( int n) { static int f=1; f=f*n; return f; } void main() { int i; for (i=1;i<=5;i++) printf ( "fun(%d)=%d\n" ,i,fun(i)); } |
1
2
3
4
5
|
fun(1)=1 fun(2)=2 fun(3)=6 fun(4)=24 fun(5)=120 |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include<stdio.h> int fun( int n) { int f=1; f = f * n; return f; } void main() { int i; for (i=1;i<=5;i++) printf ( "fun(%d)=%d\n" ,i,fun(i)); } |
1
2
3
4
5
|
fun(1)=1 fun(2)=2 fun(3)=3 fun(4)=4 fun(5)=5 |
1
2
3
4
5
6
7
8
9
10
11
12
|
public class StaticTest{ static int f= 1 ; //java声明静态变量要放到函数外面,结果和c的结果一样 int fun( int n){ f = f * n; return f; } public static void main(String[] args){ StaticTest st = new StaticTest(); for ( int i = 1 ; i <= 5 ; i++) System.out.println(st.fun(i)); } } |
原文:http://www.cnblogs.com/caffe/p/5185678.html