Skip to content

Static Keyword

Terry Griffin edited this page Nov 12, 2018 · 16 revisions

Static keyword has different meanings when used with different types. We can use static keyword with:

  1. Static Variables : Variables in a function, Variables in a class.
  2. Static Members of Class : Class objects and Functions in a class.

Static Variables in Functions

When you use the static keyword in a function (for example), this tells the compiler to allocate the variable in which static is being applied in a different part of memory. There are three types of memory that "C" uses when running a program.

  1. static: global variable storage, permanent for the entire run of the program.
  2. stack: local variable storage (automatic, continuous memory).
  3. heap: dynamic storage (large pool of memory, not allocated in contiguous order)[ 1 ].

When the static keyword is used, the variable is placed in the static portion of memory. In the example below, the count variable is placed in "static" memory and is only initialized the first time that countStuff is called. Every subsequent call continues to increment count.

void countStuff() 
{  
    // static variable 
    static int count = 0; 
    cout << count << " "; 
      
    // value is updated and 
    // will be carried to next 
    // function calls 
    count++; 
} 
  
int main() 
{ 
    for (int i=0; i<5; i++){    
        countStuff(); 
    }
    return 0; 
} 

Repl.it

Static variables in a class

class myClass 
{ 
   public: 
     static int count;
      
     myClass() 
     { 
       count++;
     }; 
}; 

int myClass::count = 0;

int main() 
{ 
  int r = rand() % 100;

  myClass myArray[100];

  cout<<myArray[rand()%100].count;

} 

Source:

  1. https://www.geeksforgeeks.org/static-keyword-cpp/
  2. https://craftofcoding.wordpress.com/2015/12/07/memory-in-c-the-stack-the-heap-and-static/
Clone this wiki locally