Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
When do function-level static variables get initialized in C/C++?
Static variables can be defined using the static keyword. They are variables that remain in memory while the program is running, meaning their lifetime is the entire program execution. This is different from automatic variables, which remain in memory only when their function is running and are destroyed when the function exits.
Function-level static variables are initialized only once − the first time the function is called. The memory for them is allocated at program load time, but the initialization occurs during the first function execution.
Syntax
static data_type variable_name = initial_value;
Example: Static Variable Initialization
This program demonstrates when static variables get initialized in C −
#include <stdio.h>
int func() {
static int num = 0;
num += 5;
printf("Inside func: num = %d\n", num);
return num;
}
int main() {
printf("Calling func() 5 times:\n");
for(int i = 0; i < 5; i++) {
printf("Call %d: %d\n", i+1, func());
}
return 0;
}
Calling func() 5 times: Inside func: num = 5 Call 1: 5 Inside func: num = 10 Call 2: 10 Inside func: num = 15 Call 3: 15 Inside func: num = 20 Call 4: 20 Inside func: num = 25 Call 5: 25
How Static Variable Initialization Works
- The static variable
numis initialized to 0 only once during the first call tofunc() - On subsequent calls, the initialization statement
static int num = 0;is skipped - The variable retains its value between function calls
- Each call increments
numby 5, showing the persistent state
Key Points
- One-time initialization: Static variables are initialized only during their first encounter
- Memory allocation: Memory is allocated at program start, but initialization happens at runtime
- Persistent state: Values are preserved between function calls
- Scope: Accessible only within the function where declared
Conclusion
Function-level static variables in C are initialized exactly once during the first function call, not on every call. This behavior makes them useful for maintaining state across multiple function invocations while keeping the variable's scope local to the function.
