使用静态变量的递归调用的不同输出

Different output on recursive call using static variable

本文关键字:输出 调用 递归 静态 变量      更新时间:2023-10-16
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;
}

谁能告诉我乐趣和乐趣之间的区别1? 获得不同的输出!!

  1. 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;
}
  1. 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++更新。