Junior
What are static variables?
sobes.tech AI
Answer from AI
Static variables in programming have the following characteristics:
- Lifetime: They exist throughout the entire runtime of the program.
- Scope: Depends on where they are defined (can be local to a function or global within a file/class).
- Initialization: They are initialized once at program startup (or upon first access, depending on the language) and retain their value between function or class method calls.
- Memory: Usually stored in the data segment of statically allocated memory.
Examples of usage:
- Counting the number of function calls.
- Storing a state shared among all instances of a class (in case of static class members).
- Implementing the Singleton pattern.
Example in C++:
#include <iostream>
void counter() {
static int count = 0; // Static local variable
count++;
std::cout << "Function called " << count << " times" << std::endl;
}
int main() {
counter(); // Output: Function called 1 times
counter(); // Output: Function called 2 times
counter(); // Output: Function called 3 times
return 0;
}
Example of a static class member in Python:
class MyClass:
class_variable = 0 # Static class variable
def __init__(self):
MyClass.class_variable += 1
def display_count(self):
print(f"Current count: {MyClass.class_variable}")
obj1 = MyClass()
obj2 = MyClass()
obj1.display_count() # Output: Current count: 2
obj2.display_count() # Output: Current count: 2