A static variable is a variable that is declared with the keyword static
within a function or class. A static variable exists for the lifetime of the program, and its value is retained between function calls or object instances.
#include <iostream>
using namespace std;
void functionSt();
int main() {
functionSt();
functionSt();
functionSt();
functionSt();
return 0;
}
void functionSt() {
static int counter = 0;
cout << "Value Atm: " << ++ counter << endl;
}
This code defines a function named functionSt()
that increments a static variable named counter
each time it is called, and prints the value of the counter to the console. The main function calls the functionSt()
function four times.
When the functionSt()
function is called for the first time, the counter
variable is initialized to 0. The ++ counter
expression increments the counter by 1, and the new value of the counter is printed to the console. On subsequent calls to functionSt()
, the counter
variable retains its previous value and is incremented again.
The fact that counter
is declared as static
means that it is initialized only once when the program starts and retains its value across function calls. If it were declared as a regular local variable, its value would be reset to 0 each time the function is called.
#include <iostream>
using namespace std;
class Cls{
public:
static int counter;
Cls() {
cout << "Value of Counter Atm: " << ++counter << endl;
}
};
int Cls :: counter = 0;
int main() {
Cls Object;
Cls Obj2;
Cls Obj3;
Cls Obj4;
return 0;
}
This code defines a class named Cls
with a static integer variable counter
. The class also has a constructor that increments the counter
variable each time an object of the class is created, and prints the current value of counter
to the console. The counter
variable is initialized outside the class definition and set to 0.
The main()
function creates four objects of the Cls
class named Object
, Obj2
, Obj3
, and Obj4
. Each time an object is created, its constructor is called, which increments the counter
variable and prints its current value.
Because the counter
variable is declared as static
within the Cls
class, it is shared by all instances of the class. This means that each time an object is created, the counter
variable is incremented, and its new value is retained for the next object.
This demonstrates how static variables can be used to share data between class instances and how they can be used to implement counting mechanisms or other forms of global state within a program.
No comments:
Post a Comment