C语言的,一个问题。

来源:百度知道 编辑:UC知道 时间:2024/05/22 04:59:06
What is the output of the following multiple-source-file program?

/*file1.c*/
-------------------------------------------
#include <stdio.h>
extern int func(int, int);
int index1= 1;
static int index2;
main(void){
int i;
for(i = 0; i < 2; i++) {
index2 = func(i, i+1);
index1 = index2 + 1;
}
printf("index1 = %d, index2 = %d\n\n", index1, index2);
return (0);
}

/*file2.c*/
-----------------------------------------------
extern int index1;
func(int i, int j) {
int k;
static int m = 2;
k = index1 + i * j * m;
m++;
return (k);
}

用VC给你运行的,不用think!!!而是一定,index1=9.index2=8

I think the output is : 7 6

I think the output is : index1=9,index2=8

vc运行
index1=9.index2=8
extern int index1; 定义为全局变量
the output is : 7 6 ??
因为m定义为static int m;
若是int m;
就应是7,6
我试过
程序运行变量空间分成两部分
局部变量和形参是临时分配的,函数结束就释放点
若 定义为int m 就是这种情况 m一直等于2
全局变量和静态变量是直到整个程序结束时才释放的
因此
定义为
static int m;
m刚开始是2
m++变成3;
func结束后,m并没有释放
下次调用func时,m=3;
故得到
index1=9,index2=8