what is static variable code example

Example 1: local static in c++

#include<iostream>

void Increment() {
	int i = 0;//The life time of variable is limited to the function scope
	i++;
	std::cout << i << std::endl;
};//This will increment i to one and when it will reach the end bracket the lifetime of var will get  destroyed
void IncrementStaticVar() {
	static int i = 0;//The life time of this var is = to program
	i++;
	std::cout << i << std::endl;
}//This will var i increment i till the program ends and i will get destroyed when program ends
int main() {
	Increment();//output 1
	Increment();//output 1
	Increment();//output 1
	IncrementStaticVar();// output 2
	IncrementStaticVar();// output 3
	IncrementStaticVar();// output 4
	IncrementStaticVar();// output 5
	std::cin.get();
}

Example 2: what is static variable

The static variable is used to refer to the common property of all objects 
(that is not unique for each object), 
e.g., The company name of employees, college name of students, etc. 
Static variable gets memory only once in the class area at the time of 
class loading. Using a static variable makes your program more 
memory efficient (it saves memory). Static variable belongs to the class 
rather than the object.

Tags:

Java Example