The static storage class in C++

C++Server Side ProgrammingProgramming

The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.

The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared.

In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class.

Example

#include <iostream>
void func( void ) {
   static int i = 10; // local static variable
   i++;
   std::cout << "i is " << i ;
   std::cout << " and count is " << count << std::endl;
}

static int count = 6; /* Global variable */

int main() {
   while(count--)
   {
      func();
   }
}

Output

This will give the output −

i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
raja
Published on 15-Feb-2018 08:02:36
Advertisements