Static variables

From Tux
Revision as of 19:22, 23 January 2018 by Williams (talk | contribs) (Created page with "The '''<code>static</code>''' keyword can be placed before the datatype in a variable declaration to create a static variable. Static variables adhere to three rules: * They...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The static keyword can be placed before the datatype in a variable declaration to create a static variable. Static variables adhere to three rules:

  • They are initialized only the first time the declaration is encountered in the program
  • They remain in memory after the scope of the variable ends
  • Despite remaining in memory, they are still only accessible within the scope of the variable

One use of a static variable is to count the number of times a function has been called as shown below:

void fcn()
{
     static int i = 0;

     cout << "This function has been called " << ++i << " times." << endl;
}

fcn();     // This function has been called 1 times.
fcn();     // This function has been called 2 times.
fcn();     // This function has been called 3 times.
fcn();     // This function has been called 4 times.
fcn();     // This function has been called 5 times.

The static keyword has other uses in C++, especially related to classes.