Tuesday, July 1, 2008

C++ quick tutorial: static

The static keyword has 3 different uses.

1. The simplest use is inside a function. If a function contains the following line:

static int count = 0;

the variable count will be set to zero only once, even if the function is called millions of times. For example, consider the following:

for (int i=0; i<1000; i++)
{
   static int count = 0;
   count++;
}

Here, the variable count is set to zero only once, not 1000 times.

2. If one file has at the top:

static float pi = 3.141592653;

then the global variable pi can be used inside just this one file. Other files are not able to access the variable pi. With just this:

float pi = 3.141592653;

then other files can access the variable pi provided they contain:

extern float pi;

3. static can also be used inside classes. For example:

class myclass
{
   int i;
}

If we then create two objects of this class:

myclass c1, c2;

then c1 and c2 will contain their own independent variable i. However, if instead we defined:

class myclass
{
   static int i;
}

and then created two objects:

myclass c1, c2;

there is only a single variable called i. Any instance of the class myclass has the same value of i. To set the value of i we can do this:

int myclass::i = 0;

The syntax is clearly of the form:

type class_name::static_variable = value

The thing here that confuses some people is that the type must be specified here as well.

No comments: