Wednesday, 9 January 2013

Static Data Member

Today, I am going to write a post on static data members in C++. I am writing this post after feeling so bad about a debugging competition which i failed once again.

Let’s see about static first.

“static”  means fixed literally. Its value is not lost even after the scope is lost. static variables.

Eg:
[sourcecode language="cpp" padlinenumbers="true"]
#include<iostream>
using namespace std;
int func()
{
static int a;
a++;
return a;
}
int main()
{
cout<< func()<<" "<<func()<<" "<<func();

}
[/sourcecode]


Output:

static

Even though the variable is declared inside func(), it is not intialized again and again. It is initialized only once.  But why the output is 3,2,1 and not 1,2,3 ?

The reason is “ Stack Evaluation”. Stack means LIFO(Last in First Out). So, the third func() will be executed first, then second, and finally first.

Rest we can see tomorrow :)

No comments:

Post a Comment