static

By postponing a local variable declaration to the static specifier, one gives indication to the compiler that the variable is to retain its value between calls to the function it belongs to. In the program reported below, the statement:

static int availableTickets = 10;
defines a variable which is initialized to 10 only the first time the function getTicket() is called. At each getTicket()call, availableTickets will contain whatever value it had the last time it exited the function. static could also be used in front of global variables to tell the compiler that such variables have to be known only within the file where they are declared. This use of static is deprecated though. Empty namespaces should be used instead. See a working example below of static applied to a local variable.

Example


#include <iostream>
using namespace std;

int getTicket()
{
     static int availableTickets = 10; // would be 0 if it were not set to 10, since it's static
     if(availableTickets)
     {
           cout << "Your ticket number is: " << availableTickets << endl;
           return availableTickets--;
     }
     else
           return 0;
}

int main()
{   
     getTicket();
     getTicket();
     getTicket();
}

Output

Your ticket number is: 10
Your ticket number is: 9
Your ticket number is: 8