I recently learnt about the static variables, that they retain their values in between various function calls. Then I wrote some code to test it, then hopefully it worked perfect. But then I accidentally removed the static keyword at the beginning of the declaration of the local variable and there came the actual problem. The output of both the programs are similar, besides the absence of the static keyword during the declaration.
Code without any static declaration:
#include <stdio.h>
void up();
int main(){
up(); //Output: 1
up(); //Output: 2
return 0;
}
void up(){
int stvar;
stvar++;
printf("%d\n", stvar);
}
Code with static declaration:
#include <stdio.h>
void up();
int main(){
up(); //Output: 1
up(); //Output: 2
return 0;
}
void up(){
static int stvar;
stvar++;
printf("%d\n", stvar);
}
Then finally I tried this one, by just initializing the local variable:
#include <stdio.h>
void up();
int main(){
up(); //Output: 1
up(); //Output: 1
return 0;
}
void up(){
int stvar = 0;
stvar++;
printf("%d\n", stvar);
}
This time the local variable shows it natural behaviour. I just wanted to know if uninitialized local variables are static by default?