The static keyword in C++ is used to control the scope of program elements. It allows certain members to belong to the class or file rather than to individual objects or function calls.
- Restrict visibility or ownership of members at the class or file level
- Provide shared behavior or data that does not depend on object instances
1. Static Variables in a Function
When a variable inside a function is declared as static, it is allocated once for the entire lifetime of the program rather than on each function call. Its value persists between function calls, so the variable retains the value from its previous invocation instead of being reinitialized. The static variables in a function have the following applications:
- Return local variable address from the function.
- Useful for implementing coroutines in C++ or any other application where the previous state of a function needs to be stored.
- Memoization in recursive calls.
Example:
#include <bits/stdc++.h>
using namespace std;
void f() {
// Static variable
static int count = 0;
count++;
cout << count << " ";
}
int main() {
// Calling function f() 5 times
for (int i = 0; i < 5; i++)
f();
return 0;
}
Output
1 2 3 4 5
Explanation: Since count is declared as static, it keeps its value between function calls, so it is not reset every time the function runs.
Note: Java doesn't allow static local variables in functions.
2. Static Data Member in a Class
As the variables declared as static are initialized only once as they are allocated space in separate static storage so, the static member variables in a class are shared by the objects. There cannot be multiple copies of the same static variables for different objects. Also because of this reason static variables cannot be initialized using constructors. The static data members can be used to implement the following:
- Counting Objects of a Class
- Store and share configuration or settings globally.
- Tracking Shared Resources
- Regulate or limit operations performed by multiple objects.
- Ensure a class has only one instance by using static members.
Example:
#include <iostream>
using namespace std;
class GfG {
public:
static int i;
GfG(){
// Do nothing
};
};
int main() {
GfG obj1;
GfG obj2;
obj1.i = 2;
obj2.i = 3;
// Prints value of i
cout << obj1.i << " " << obj2.i;
}
Output
undefined reference to `GfG::i'
collect2: error: ld returned 1 exit status
Explanation: You can see in the above program that we have tried to create multiple copies of the static variable i for multiple objects. But this didn't happen.
So, a static variable inside a class should be initialized explicitly by the user using the class name and scope resolution operator outside the class as shown below:Â
#include <iostream>
using namespace std;
class GfG {
public:
static int i;
GfG(){
// Do nothing
};
};
// Static member inintialization
int GfG::i = 1;
int main() {
// Prints value of i
cout << GfG::i;
}
Output
1
Explanation: We were able to access the static variable when is was initialized globally outside the class. Moreover, we can access the static data member without creating the object of the class.
3. Static Member Functions in a Class
Static member functions belong to the class rather than to any object and should be called using the class name with the scope resolution operator (::). They can access only static data members and other static member functions, and cannot access non-static members of the class. The static member functions have the following uses in C++:
- Accessing Static Member Variables
- Implement helper functions that do not depend on specific instances.
- Singleton Pattern Implementation
- Factory Methods to create and return objects without requiring an instance of the class.
- Logging and Debugging
Example:
#include <iostream>
using namespace std;
class GfG {
public:
// Static member function
static void printMsg() { cout << "Welcome to GfG!"; }
};
int main() {
// Invoking a static member function
GfG::printMsg();
}
Output
Welcome to GfG!
Explanation: printMsg() is a static member function, so it belongs to the class rather than any object and is correctly called using GfG::printMsg(), printing the message without creating a class instance.
4. Global Static Variable
A global static variable in C++ is a static variable declared outside of any class or function. Unlike regular global variables, a global static variable has internal linkage, meaning it is accessible only within the file where it is defined. This ensures that its scope is limited to the current translation unit, preventing conflicts with variables in other files that may have the same name. The global static variables have the following uses in C++:
- Limiting variable scope to a file to prevent conflicts by ensuring the variable is accessible only within the file.
- Global counters or flags.
- Store settings or values that are specific to the functionality implemented in a single file.
- Use for shared resources in scenarios where frequent initialization and destruction can be avoided.
- Shared state across functions in a file.
Example:
#include <iostream>
using namespace std;
// Global static variable
static int count = 0;
void increment() {
count++;
cout << count << " ";
}
int main() {
increment();
increment();
return 0;
}
Output
1 2
Explanation: Here, count is a static global variable, so it is created only once and retains its value for the entire program. Each call to increment() increases the same shared count, producing cumulative output.