Static int vs regular int

Hi,
I've been looking on Google and get really confused on how people describe the difference of static int and regular int, does anyone mind dumbing it down for me? static just really confuses me..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// static1.cpp
// compile with: /EHsc
// taken from microsoft
#include <iostream>

using namespace std;
void showstat( int curr ) {
   static int nStatic;    // Value of nStatic is retained
                          // between each function call
   nStatic += curr;
   cout << "nStatic is " << nStatic << endl;
}

int main() {
   for ( int i = 0; i < 5; i++ )
      showstat( i );
}

I've been testing and when i don't use static, i get crazy numbers like 2293728
because you dont have initialize of it :
static int nStatic = ?;

change it to :
static int nStatic = 0;
in static and non-static
and test it again
Last edited on
Local variables are not initialized to zero, but statics (and globals) are.
oh, so basically...
static int asdf

and

int asdf = 0

are the same?

that's weird, i wonder why all variables aren't just auto initialized to zero
Last edited on
your answer is :
garbage
of course this is relative to compiler !!! in vc++ compiler the static member initialize with zero but this is not one a rule as i know !!
@andywestken are you sure this is a general rule ?
Last edited on
It is not a VC++-ism.

Stroustrup "The C++ Programming Language " states that :

"Where a static variable is initialized with an expression that is not a constant-expression, default initialization to 0 of the appropriate type happens before the block is first entered."
umm ok tnx i have a little problem with details :D
Topic archived. No new replies allowed.