Junior — Middle
How does the use of the static keyword affect the scope and lifetime of local variables in a program?
sobes.tech AI
Answer from AI
The keyword static when declaring a local variable inside a function changes the variable's lifetime and scope.
- Scope: The variable remains local to the function, meaning it is only accessible within that function.
- Lifetime: The variable exists throughout the entire runtime of the program, not just during the function call.
This means that the value of such a variable is preserved between function calls.
Example:
#include <stdio.h>
void func() {
static int count = 0; // initialized once
count++;
printf("Count: %d\n", count);
}
int main() {
func(); // Count: 1
func(); // Count: 2
func(); // Count: 3
return 0;
}
In this example, the variable count retains its value between calls to func thanks to static.