Static variables and global variables in C++ both have static storage duration, meaning they exist for the lifetime of the program. However, there are key differences between them in terms of scope, usage, and encapsulation.
Example of a global variable:
#include <iostream>
int globalVar{100};
void printGlobal() {
std::cout << "Global Variable: "
<< globalVar << "\n";
}
int main() {
printGlobal();
globalVar = 200;
printGlobal();
}
Global Variable: 100
Global Variable: 200
Example of a static variable:
#include <iostream>
#include <string>
class Vampire {
public:
static inline std::string Faction{"Undead"};
};
void printFaction() {
std::cout << "Faction: "
<< Vampire::Faction << "\n";
}
int main() {
printFaction();
Vampire::Faction = "Demonic";
printFaction();
}
Faction: Undead
Faction: Demonic
In summary, static variables provide better encapsulation and scope control compared to global variables, making them preferable for shared data within classes.
Answers to questions are automatically generated and may not have been reviewed.
A guide to sharing values between objects using static class variables and functions