Wednesday 17 February 2016

Static local variables in C++

The concept of static local variable was present in C programming language. But in C++ we have two new concepts related to static keyword. In C++ we have concept of static member variable and static member function. But here in this post I will tell you about the static local variable.

Key points:

  • Concept as is taken from C.
  • They are by default initialized to zero..
  • Their lifetime is through out the program.
  • But their scope is limited to that block only where it is declared.
  • Meaning of static local variable is " declaration of a variable qualified with static keyword into a block/function of program.
  • Example:

void fun()
{
    int y;
    static int x; // static local variable
}

Things that should always be kept in mind about static variable is :

  • Its by default value is 0.
  • Its lifetime is throughout the program.
  • In the above function variable 'y' is not static and thus the variable 'y' will get memory only when fun() is called. But variable 'x' gets the memory at the time of start of the program.
  • Although its lifetime is throughout the program , but its scope is limited to the block where it is declared.


For more information you can visit here.

1 comment: