Department of Engineering

IT Services

C++ and static

The static keyword is used in 3 contexts for 3 reasons.

  • Privacy (in files) - if at the top of a file you have "int i;" then not only can all the file's functions access the variable, but functions in other files can too (as long as the other files contain "extern int i;"). Using "static int i;" restricts access so that the variable can't be accessed externally. The same idea applies to functions: "static int foo() { ....} " is a function returning an int that can only be called from the file it's in. These protected items are said to have "internal linkage".
    Note that const "variables" by default have "internal linkage". To illustrate the point here are 4 situations where 2 files - file1.cc and file2.cc - are compiled together. Sometimes the cloud variable in file2.cc can be used from file1.cc, sometimes it can't.
    file1.ccfile2.ccg++ file1.cc file2.cc
    int main() {
       int i=cloud;
    }

    int cloud=9;file1.cc:2: error: cloud was not declared in this scope
    extern int cloud;
    int main() {
       int i=cloud;
    }

    int cloud=9;(compiles ok)
    extern int cloud;
    int main() {
       int i=cloud;
    }

    const int cloud=9;link error: undefined reference to `cloud'
    extern int cloud;
    int main() {
       int i=cloud;
    }

    extern const int cloud=9;(compiles ok)
  • Permanence (in functions) - variables created within a function are by default "automatic", meaning that they disappear when the function ends. Sometimes however, you'd like the variable to persist. For example, in the following code the count variable is used to count how many times the counter routine's called. The variable's set initially to 0 but is incremented each time after that. Without the static keyword, the variable would be repeatedly reset to 0.
      int counter() {
         static int count=0;
         count++;
         cout << count << endl;
      }
    
  • Ownership (in classes) - In the following code a class is defined that has 1 member.
      class little {
         int i;
      };
    
    "little l1, l2;" would create 2 objects of that class, each with their own i variable. In contrast,
      class little {
         static int i;
      };
      little l1, l2;
    
    creates 2 objects but only 1 variable called i - the i belongs to the class rather than to individual objects. This is useful if, for example, you want to keep a count of how many objects of a particular class have been created. In some situations it also saves memory. Class functions can also be static.