how to declare a static variable in c++ code example

Example 1: static in class c++

#include <iostream>

class Entity {
public:
	static int  x,y;
	static void Print() {
		std::cout << x << ", " << y << std::endl;
	}// sta1tic methods can't access class non-static members
};
int Entity:: x;
int Entity:: y;// variable x and y are just in a name space and we declared them here
int main() {
	Entity e;
	Entity e1;
	e.x = 5;
	e.y = 6;
	e1.x = 10;
	e1.y = 10;
	e.Print();//output => 10 because variable x and y being static point to same block of memory
	e1.Print();//output => 10 because variable x and y being static point to same block of memory
	Entity::x;	//you can also acess static variables and functions like this without creating an instance
    Entity::Print();	//you can also acess static variables and functions like this without creating an instance
	std::cin.get();
}

Example 2: 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();
}

Tags:

Misc Example