全部博文(7)
2008年(7)
分类: C/C++
2008-03-20 13:32:06
静态局部变量
1 #include
2
3 int array_sum(int x[],int n)
4 {
5 static int sum;/* 只声明,不初使化 */
6 static int i;
7
8 sum = 0;
9
10 for (i = 0; i < n; i++)
11 {
12 sum += x[i];
13 }
14
15 return sum;
16 }
17
18 int
19 main(void)
20 {
21 int arr_a[] = {1, 2, 3, 4, 5};
22 int arr_b[] = {6, 7, 8, 9};
23 int s = 0;
24
25 s = array_sum(arr_b,4) + array_sum(arr_a,5);
26 printf("sum = %d\n", s);
27 exit(0);
28 }
[root@mylinux ~]# gcc temp.c
[root@mylinux ~]# ./a.out
sum = 45
然而
1 #include
2
3 int array_sum(int x[],int n)
4 {
5 static int sum = 0;/* 初使化为0 */
6 static int i;
7
8 for (i = 0; i < n; i++)
9 {
10 sum += x[i];
11 }
12
13 return sum;
14 }
15
16 int
17 main(void)
18 {
19 int arr_a[] = {1, 2, 3, 4, 5};
20 int arr_b[] = {6, 7, 8, 9};
21 int s = 0;
22
23 s = array_sum(arr_b,4) + array_sum(arr_a,5);
24 printf("sum = %d\n", s);
25 exit(0);
26 }
[root@mylinux ~]# gcc temp.c
[root@mylinux ~]# ./a.out
sum = 75
去掉static关键字
1 #include
2
3 int array_sum(int x[],int n)
4 {
5 int sum = 0;
6 static int i;
7
8 for (i = 0; i < n; i++)
9 {
10 sum += x[i];
11 }
12
13 return sum;
14 }
15
16 int
17 main(void)
18 {
19 int arr_a[] = {1, 2, 3, 4, 5};
20 int arr_b[] = {6, 7, 8, 9};
21 int s = 0;
22
23 s = array_sum(arr_b,4) + array_sum(arr_a,5);
24 printf("sum = %d\n", s);
25 exit(0);
26 }
[root@mylinux ~]# gcc temp.c
[root@mylinux ~]# ./a.out
sum = 45