Cpp Static Variables

Introduction

A variable with file scope can be accessed by any function or block within a single file. To declare a file scoped variable, use static.

Using the static keyword on local variables changes them from automatic duration to static duration. A static duration variable is one that retains it's value even after the scope in which it has been created has been exited.

Examples

Example 1

#include <iostream>
 
void IncrementAndPrint()
{
        using namespace std;
        int nValue = 1; // automatic duration by default
        ++nValue;
        cout << nValue << endl;
} // nValue is destroyed here
 
void IncrementAndPrintStatic()
{
        using namespace std;
        static int s_nValue = 1;
        ++s_nValue;
        cout << s_nValue << endl;
}//s_nValue is not destroyed here, but becomes inaccessible
int main()
{
        using namespace std;
 
        cout << "Using a non static variable..." << endl;
        IncrementAndPrint();
IncrementAndPrint();
        IncrementAndPrint();
 
        cout << "Using a static variable..." << endl;
        IncrementAndPrintStatic();
        IncrementAndPrintStatic();
        IncrementAndPrintStatic();
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.