i just started programming in c++ this concept of static variable/function wasn\'t clear to me..why is this used and is there any other alternative of this!!!
The static keyword specifies that the life-time of the given the variable, function or class is application-wide. Like having a single instance.
This example might illustrate it:
#include
using namespace std;
void test() {
static int i = 123;
if (i == 123) {
i = 321;
}
cout << i << endl;
}
int main(int arg, char **argv) {
test();
test();
return 0;
}
The output is:
321
321
So "i" is only initialized the first time it is encountered, so to speak. But actually it's allocated at compile time for that function. Afterwards, it's just in the scope of the function test() as a variable, but it is static so changing it changes it in all future calls to test() as well.
But I encourage you to read more about it here: http://www.cprogramming.com/tutorial/statickeyword.html