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]
#include<iostream>
using namespace std;
int func()
{
static int a;
a++;
return a;
}
int main()
{
cout<< func()<<" "<<func()<<" "<<func();
}
[/sourcecode]
Output:
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