I get garbage values when i don't declare the variable as static in my function and call it from main method.
OUTPUT: http://postimg.org/image/rufgh6tsx/
Code without static variable(nStatic):
1 2 3 4 5 6 7 8 9 10
void showstat(int curr) {
int nStatic;
nStatic += curr;
cout << "nStatic is " << nStatic << endl;
int main() {
for(int i = 0; i < 5; i++) {
showstat(i);
}
return 0;
}
Code with static variable:
1 2 3 4 5 6 7 8 9 10
void showstat(int curr) {
staticint nStatic;
nStatic += curr;
cout << "nStatic is " << nStatic << endl;
int main() {
for(int i = 0; i < 5; i++) {
showstat(i);
}
return 0;
}
Could someone explain me what is happening behind the scenes?
Thank you
I'm guessing the first bullet point applies, though it doesn't explicitly say so:
"When you declare a variable, the variable has static duration and the compiler initializes it to 0 unless you specify another value."
When you don't declare it as static, it isn't initialized to anything so you get garbage.