Wednesday, March 24, 2010

Static Keyword in C++

The static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified.But, initialize it with 0 if you want to, to avoid confusion
A variable declared static in a function retains its state between calls to that function.
The keyword static can be used in three major contexts: inside a function, inside a class definition, and in front of a global variable inside a file making up a multifile program.

Inside a Function:

The keyword static prevents re-initialization of the variable.
For example:

#include

using namespace std;
void showstat( int curr ) {
static int nStatic = 0;
nStatic += curr;
cout << "nStatic is " << nStatic << endl; }
int main()
{
for ( int i = 0; i < 5; i++ )
showstat( i );
}

Run this once and again run it without static keyword. You'll understand the difference. Inside a class:

To access the static member, you use the scope operator, ::, when you refer to it through the name of the class.
One cannot initialize the static class member inside of the class.
Static member functions can only operate on static members, as they do not belong to specific instances of a class.

Inside a File:

The use of static indicates that source code in other files that are part of the project cannot access the variable. Only code inside the single file can see the variable. (It's scope -- or visibility -- is limited to the file.)

No comments:

Post a Comment