Static variables

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) {
	static int 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
You should get garbage variables in both cases because nStatic isn't initialized to anything.

I see you were looking at this: http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx

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.
Last edited on
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 #include <iostream>
 
 void showstat(int curr) {
	int nStatic;
	nStatic += curr;
	std::cout << "nStatic is " << nStatic << std::endl;
  }
  
  int main() {
        for(int i = 0; i < 5; i++) {
		showstat(i);
	}
        return 0;
  }
Topic archived. No new replies allowed.