Showing posts with label static. Show all posts
Showing posts with label static. Show all posts

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...

Monday, February 4, 2013

C++ 'in class variable' and 'static variable' initialization

#include <iostream>
using namespace std;

class Demo

{
  public:
  int a  = 1;
    // static int b=2;  //this gives error
  static int b;
};

int Demo::b=2;  //initialize the static variable of class

int main()
{
    Demo d;
    cout << "\n value of variable a: " << d.a << endl;
    cout << "\n value of static variable b: " << Demo::b << endl;
}


OUTPUT:

Thursday, December 20, 2012

Program to show static variable not goes in the memory of object

#include <iostream>
using namespace std;

class laptop
{
    int first_int;           //size of int is 4 byte
    int second_int;       // Means size of this class is 8 Byte
};

class car
{
    static int first_int;
            int second_int;
};

int main()
{
    laptop dell;
    car santro;
   
    cout << sizeof(dell) << endl;
    cout << sizeof(santro) << endl;
}


OUTPUT:
8


This Program show static variable not goes in the memory of object static variable is the only belonging of class.

Wednesday, October 17, 2012

Program to understand STATIC variable

Static is multipurpose keyword, we can use static in context of variable, function and classes.
Here we discuss about the static variable.
__________________________________________________________________
//In this program we are not using static variable 
 #include<stdio.h>
#include<conio.h>

void show()
{
    int i=0;          //Note, we are not declaring 'i' as a static variable here
    i++;               //variable 'i' increased by 1


    printf("output is %d\n" ,i);
}

void main()
{
    show();            //here we are calling show 3 times
    show();
    show();
}


output:
       output is 1
       output is 1

       output is 1

You can see that  output is 1, although we are calling show function 3 time.
That because the variable i not retaining the value.

  •  So to retain the value we use this variable as a static variable. (see next program)
  •  Static variable is useful when we want to count the no of attempt performed by the client. (see last program)
__________________________________________________________________
//using STATIC variable
#include<stdio.h>
#include<conio.h>

int show()
{
    static int i=0;            //here we use static variable
             i++;
             printf("output is %d\n" ,i);
}

void main()
{
    show();
    show();
    show();
}

output:
          output is 1
          output is 2
          output is 3

__________________________________________________________________
//In this program we want that user have only 4 chance to enter right password
#include<iostream>
#include<string>
#include<stdlib.h>              //for exit(0);
using namespace std;

int show()
{
     static int i=0;            //here we use static variable
           // int i=0;


    
string password;           
     i++;
                      
            if(i<=3)
            {
                cout << "\nenter your password: ";
                cin >> password;
               
                if (password == "foobar")
                    {
                        cout << "\nwelcome you log in!\n";
                        exit(0);
                    }
            }
  
            else
            {
                cout << "recover your password";
            }
           
}

int main()
{
    show();              //here we can use the loop also
    show();
    show();
    show();
}

Friday, September 28, 2012

code to illustrate static function

#include <iostream>
#include <string>
using namespace std;

class Cat
{
    public:
        static int Add(int a, int b)
        {
            return a+b;
        }
};

int main()
{
    cout << "\n" << Cat::Add(5,67) << endl;
    return 0;
}


OUTPUT:

In this example we don't have to create an object of class to access the static function.

Sunday, September 23, 2012

A note on Stack and Heap

  • Stack-memory and Heap-memory are physically the same.
  • The RAM may be used as stack memory when running one program and later used as heap memory when running some other program.
  • The difference is in how they are used.
Difference between Stack vs Heap memory:
 

Stack:
  • Often a function or method calls another function which in turn calls another  function etc.
  • The execution of all those functions remains suspended until the very last function returns its value.
  • All the information required to resume the execution of these functions is stored on the stack.
  • In particular, local variables are stored on the stack.
  1. Local variables are often stored for short amounts of time while a function/method block uses them to compute a task.
  2. Once a function/method has completed its cycle, the space on the stack used by all local variables is freed.
  • This chain of suspended function calls is the stack, because elements in the stack (function calls) depend on each other.
  • The stack is important to consider in exception handling and thread executions.

Heap:
  • The heap is simply the memory used by programs to store global variables. or All global variables are stored in heap memory.
  • Element of the heap (variables) have no dependencies with each other and can always be accessed randomly at any time.
  • All variables dynamically created by the program with "new()" or "malloc()" or similar commands are also stored on the heap.
  • In some programming languages, all instances of an object, including all the attributes of that instance, are stored on the heap (java).
  • In those programming languages, local variables of a function that have object type are implemented as creating the new object on the heap, and storing a reference to that object in the local variable, which is on the stack.
  • When that function exits, the heap memory used by each local variable that has object is freed, and then all the stack used by that stack is freed.

Similarties:
  • Both are used for providing memory to a program at run time.
  • both reside in main-memory (RAM)
  • both are datastructure (used to organised data)

Thursday, September 20, 2012

How to count the number of objects created of a class

#include <iostream>
using namespace std;

class Demo
{
    public:
        static int totalObject;
       
        Demo()
        {
            totalObject++;
        }
};

int Demo::totalObject(0);    //static variable initialized to 0

int main()
{
    Demo d1;
    Demo d2;
    Demo d3;
    Demo d4;
   
    cout << "\n Total no of object of Demo class is: " << Demo::totalObject << endl;
    return 0;
}


OUTPUT: