Thursday, February 7, 2013

Why static Variable auto intialize to 0

Ans. Because It's not goes in the stack memory area.

Fact that u must know before this program:
        1. GLOBAL and STATIC variable auto initialize to 0
        2. Global Variable text-segment m jata hai.

-----------------------------------------------------------------------------------------------
 Note: in blue color is actual code rest code is to get clear output
#include <iostream>
using namespace std;

    int normalLocal;              //global variable
    static int normalLocalStatic; //global static variable
   
    class Demo
    {
        public:
            int classInstance;
            static int classInstanceStatic;
    };
   
    int Demo::classInstanceStatic;
   
    void test()
    {
        int functionLocal;
        static int functionLocalStatic;
       
        cout << "\n    functionLocal is : " << functionLocal <<endl;
        cout << "\nfunctionLocalStatic is : " << functionLocalStatic <<endl;
    }
   
    class DemoHeap
    {
        public:
            int classHeapInstance;
            static int classHeapInstanceStatic;
    };
   
    int DemoHeap::classHeapInstanceStatic;

int main()
{
    int mainLocal;
    static int mainLocalStatic;

   
    cout << "\n\n-----------just below header files (Means global area)-------------" << endl;
    cout << "\n       normalLocal is : " << normalLocal  

           << "\t Please Notice this is GLOBAL variable" <<endl;
    cout << "\n normalLocalStatic is : " << normalLocalStatic  

           << "\t Please remember STATIC variable" <<endl;
   
    cout << "\n\n-----------Inside function-------------" << endl;
    test();
       
    Demo d;    //This makes object on stack
    cout << "\n\n-----------This object on stack-------------" << endl;
    cout << "\n      classInstance is : " << d.classInstance << endl;
    cout << "\nclassInstanceStatic is : " << d.classInstanceStatic << endl;

   
    cout << "\n\n-----------Inside Main-------------";
    cout << "\n         mainLocal is : " << mainLocal << endl;
    cout << "\n   mainLocalStatic is : " << mainLocalStatic << endl;

   
   
    DemoHeap * dh = new DemoHeap(); //This makes object on heap
    cout << "\n\n-------This object on heap-------------" << endl;
    cout << "\n        classHeapInstance is : " << dh->classHeapInstance 

           << "  surprise(local var auto-intializ to 0)" << endl;
   cout << "\n  classHeapInstanceStatic is : " << dh->classHeapInstanceStatic << endl;
    delete dh;
    dh = 0;

   
    return 0;
}

OUTPUT:

Moral of the story:
  1.  jo variable stack m jayega vo default garbage value lega;(ab samjha java har variable aotu 0 kyu hota hai)
  2. jo variable static or heap or text-segment m jayega vo aotu 0 initialized ho hoga.
  3. isliye global and static variable kahi bhi ho vo auto 0 initialized hote hai.
For more on Stack and Heap...

No comments:

Post a Comment