int fun1(int x){
static int n;
n = 0;
if(x > 0){
n++;
return fun1(x-1)+n;
}
return 0;
}
int fun(int x){
static int n = 0;
if(x > 0){
n++;
return fun(x-1)+n;
}
return 0;
}
有人能告诉我fun和fun1之间的区别吗?获得不同的输出!
static int n = 0;
是一次初始化像摘要一样,
bool initialized = false;
static int n;
int fun1(int x){
if(!initialized){
n = 0;
initialized = true;
}
if(x > 0){
n++;
return fun1(x-1)+n;
}
return 0;
}
static int n; n =0
在每个递归调用中都重置为零。如下所示, bool initialized = false;
static int n;
int fun(int x){
if(!initialized){
n = 0;
initialized = true;
}
n = 0;
if(x > 0){
n++;
return fun(x-1)+n;
}
return 0;
}
实际上n
是.BSS的一部分,并在加载时初始化为零。
在fun1
中,每次调用该函数时,n
都设置为0
。
在fun
中,n
在程序启动时初始化为0
,但此后仅由n++
更新。
在fun1中,每当调用fun1时,您就使n = 0有趣的是,它将值重新获得为n ++,即仅将其初始化为0一次