Static Data & Functions in C/C++

Static Data in C:

If you declare the variable as static inside the functions,that variable retain the information between calls to a function.This static data variable is stored in Data Segment of the Memory.
                   If the static variable is initialized,stored in Data Segment
                   If not,Stored in BSS(Block started by Symbol) segment.

Static variables are automatically initialized to zero upon memory allocation.Static storage class can be specified for automatic as well as external variables.

The scope of static automatic variables is identical to that of automatic variables, i.e. it is local to the block in which it is defined; however, the storage allocated becomes permanent for the duration of the program. Static variables may be initialized in their declarations; however, the initializers must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable.

Static Arrays:
We can apply static to a local array declaration so the array is not created and initialized each time the function is called and the array is not destroyed each time the function is exited in the program.
This reduces program execution time particularly for programs with frequently called functions that contain large arrays.


    Example Program:
/* Program which sums integers, using static variables */ 
#include <stdio.h>
#define MAX 5 
void sumIt(void); 
int main() 
{
           int i =0;
           printf("Enter 5 numbers to be summed\n"); 
           for(i = 0; i<MAX; ++i) 
                   sumIt(); 
           printf("Program completed\n"); 
           getchar(); 
         return 0; 
}
void sumIt(void) 
           static int sum = 0;
           int num; 
           printf("\nEnter a number: ");  
           scanf("%d", &num); 
           sum+=num;
           printf("The current sum is: %d",sum); 
}

 
Static Arrays Example Program:  
Function staticArrayInit has a local static array and function automaticArrayInit has an automatic local array.

#include <stdio.h>
 /* Static arrays are initialized to zero */ 
void staticArrayInit( void );
void automaticArrayInit( void );
int main()
{
       printf( "First call to each function:\n" ); 
       staticArrayInit(); 
       automaticArrayInit();
       printf( "\n\nSecond call to each function:\n" );
       staticArrayInit(); 
       automaticArrayInit();
     return 0; \
/* function to demonstrate a static local array */ 
void staticArrayInit( void ) 
       static int a[ 3 ]; 
       int i; 
       printf( "\nValues on entering staticArrayInit:\n" ); 
       for ( i = 0; i <= 2; i++ )
             printf( "array1[%d] = %d ", i, a[ i ] );
             printf( "\nValues on exiting staticArrayInit:\n" );
       for ( i = 0; i <= 2; i++ ) 
             printf( "array1[%d] = %d ", i, a[ i ] += 5 ); 
/* function to demonstrate an automatic local array */ 
void automaticArrayInit( void ) 
{
       int a[ 3 ] = { 1, 2, 3 }, i; 
       printf( "\n\nValues on entering automaticArrayInit:\n" ); 
       for ( i = 0; i <= 2; i++ ) 
             printf("array1[ %d ] = %d ", i, a[ i ] ); 
             printf( "\nValues on exiting automaticArrayInit:\n" );
       for ( i = 0; i <= 2; i++ ) 
             printf( "array1[ %d ] = %d ", i, a[ i ] += 5 ); 
}

Static Data in C++:

We all knew that,each object contains its own copy of the data members,where as ,the member functions are shared amongst all objects.

If a data member of a class is declared as static,then only one copy is created for the entire class,irrespective of the number of objects created from that class.Static member is useful when all the objects of the same class must share a common item of information.Static data member is available only with in the class,but it continues to live till the time program execution doesn't come to end.

      Example Program:
#include<iostream> 
class sample 
{
        static int count; //declaration of static variable
        int index; 
        public: 
                  sample() 
                  { 
                         count++; 
                         index++;
                  } 
                  void showdata()
                  { 
                         cout<<endl<<"count="<<count;
                         cout<<endl<<"index="<<index; 
                  } 
 };
 int sample::count=0; //definition of static variable count 
void main() 
{
      sample s1,s2; 
      s1.showdata(); 
      s2.showdata(); 
}
       Output:
             count=2;
             index=-2345;
             count=2;
             index=654;

Here,static data declared inside the class and defined in outside the class.
why such an approach is used for static data members?
If static date members were defined inside the class declaration it would violate the idea that a class declaration is only a blueprint and does not set aside any memory.

Defining the static member data out side the class also emphasizes two facts.
1) The memory space for such data is allocated only once,before program starts executing.
2) There is only one static member variable for the entire class.

When would we be required to use static member data?
Imagine a situation where an object is required to know how many other objects of its class are in existence.

Static Functions in C:

Generally,normal member functions will be accessible to through out  the program.If we declare the member function as static,that function can not be accessed by out side the file,only within the file can be accessed.

Static Functions in C++:
The main usage of static function is when we want to have a function which is accessible even when the class is not instantiated.
Static member functions have a class scope,they don't have access to 'this' pointer of a class.

Static functions are accessed using only the class name and the scope resolution operator.
Static member functions can only access static data.
Static member functions can not be declared as virtual.

   Example Program:
#include<iostream> 
class sample
        static int count; 
        public: 
                  sample() 
                  { 
                         count++;
                  } 
                  static void showdata() 
                  { 
                         cout<<endl<<"count="<<count; 
                   } 
};
int sample::count=0;
void main() 
        sample s1; 
        sample::showdata(); 
        sample s2; 
        sample::showdata();
}

No comments:

Post a Comment