Stattic Variable Example Program Example using CPP
- Home
- Tutorials
- CPP
- CPP Programs
- Variables
- Program
Source Code
#include <iostream>
using namespace std;
// function prototype/declaration
int testVariables ();
int main(int argc, char** argv) {
// function calls
testVariables();
testVariables();
return 0;
}
// function defination
int testVariables () {
static int s = 1 ;
auto int a = 1 ;
cout<<"Value of Local Variable: "<<a<<endl;
cout<<"Value of Static Variable: "<<s<<endl;
s = s + 1 ;
a = a + 1 ;
}
Output
Working
Static variable are declared with static storage class. These variable may be of any type such as int, float, double or char. Static variable retain it's value either the control transfer out of function. In this program we use function named as testVariables(). Then we declare two variables, one of auto and other of static storage class. In funcion body we initialize both variables and then print their values. After printing values we increase their values by one.
Static variables use declaration/initialization statement only one. Whenever these variables are accessed they retain their previous value.