STATIC OBJECTS IN FUNCTIONS


#include "stdafx.h"
#include "iostream"
#include "cstdlib"
#include "ctime"
using namespace std;
void LovesMeNot() {
       static bool LovesMe = false;
       LovesMe = !LovesMe;
       if (LovesMe){
             cout << "Loves Me!" << endl;
       }
       else{
             cout << "Loves Me Not!" << endl;
       }
}
int _tmain(int argc, _TCHAR* argv[])
{
       srand(time(0));
       int i = rand() % 10 + 1;
       while (i--)
             LovesMeNot();
       system("pause");
       return 0;
}


If we remove static from the declaration of variable LovesMe then the variable LovesMe would be on each entry in the function initialized to the same value (false) and every function call made to print the same message:
#include "stdafx.h"
#include "iostream"
#include "cstdlib"
#include "ctime"
using namespace std;

void LovesMeNot() {
       bool LovesMe = false;
       LovesMe = !LovesMe;
       if (LovesMe){
             cout << "Loves Me!" << endl;
       }
       else{
             cout << "Loves Me Not!" << endl;
       }
}

int _tmain(int argc, _TCHAR* argv[])
{
       srand(time(0));
       int i = rand() % 10 + 1;
       while (i--)
             LovesMeNot();
       system("pause");
       return 0;
}

Static object exists in the function during whole time of program execution, but they are available only inside the function in which they are declared. We can imagine these static objects that they are declared outside the function using special class static and can be only accessed only using function in which they are declared. That's why we use the same keyword static: the placement of this objects and global static objects is carried out in the same way so static objects will have the same initial value 0 if they are not initialized otherwise.


Share on Google Plus