C++ static Specifier

Introduction

The static specifier says the object will have a static storage duration.

The memory space for static objects is allocated when the program starts and deallocated when the program ends.

Only one instance of a static object exists in the program.

If a local variable is marked as static, the space for it is allocated the first time the program control encounters its definition and deallocated when the program exits.

To define a local static variable inside a function we use:

#include <iostream> 

void myfunction() 
{ 
    static int x = 0; // defined only the first time, skipped every other   
                      // time 
    x++; /*from   ww w. j ava2s  .c o  m*/
    std::cout << x << '\n'; 
} 

int main() 
{ 
    myfunction(); // x == 1 
    myfunction(); // x == 2 
    myfunction(); // x == 3 
} 

This variable is initialized the first time the program encounters this function.

The value of this variable is preserved across function calls.

What does this mean? The last changes we made to it stays.

It will not get initialized to 0 for every function call, only the first time.

This is convenient as we do not have to store the value inside some global variable x.




PreviousNext

Related