static int n = 0;
is one time initialization
Like the snippet below,
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
is reset to zero on every recursive call. Like below,
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;
}
In reality n
is part of .BSS and initialized to zero at load time.
11
solved Different output on recursive call using static variable [closed]