Junior — Middle
What is the difference between a static variable and a regular variable in programming?
sobes.tech AI
Answer from AI
A static variable differs from a regular variable in that it retains its value between function calls or throughout the entire runtime of the program, whereas a regular variable is recreated each time and destroyed after exiting its scope.
For example, in Swift, a static variable inside a class or structure belongs to the type itself, not to an instance, and exists as a single instance:
class Counter {
static var totalCount = 0
var count = 0
func increment() {
count += 1
Counter.totalCount += 1
}
}
let a = Counter()
a.increment()
print(a.count) // 1
print(Counter.totalCount) // 1
let b = Counter()
b.increment()
print(b.count) // 1
print(Counter.totalCount) // 2
Here, count is a regular instance variable, and totalCount is a static variable shared among all instances of the class.