Junior — Middle
Where are static variables usually stored in a program?
sobes.tech AI
Answer from AI
Static variables in a program are usually stored in the data segment or the initialized data segment of the process memory. This is a memory area allocated for storing global and static variables that exist throughout the program's runtime.
In iOS (and generally in C/C++/Objective-C), static variables inside functions or classes are stored in this area, not on the stack or heap. This allows them to retain their value between function calls.
Example:
func counter() -> Int {
static var count = 0
count += 1
return count
}
print(counter()) // 1
print(counter()) // 2
Here, count is a static variable stored in the data segment and retains its value between function calls.