'Different output on recursive call using static variable [closed]
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;
}
Can anyone tell me the difference between fun and fun1 ? Getting different output!!
Solution 1:[1]
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 =0is 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.
Solution 2:[2]
In fun1, n is set to 0 every time the function is called.
In fun, n is initialised to 0 at program start but thereafter only updated by n++.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | xxx |
| Solution 2 | cpcallen |
