In C programming language, a static variable is a variable that is allocated memory once, and its value persists across function calls. Here are some of the key differences between a static variable and a regular variable:
Scope: A static variable has local scope, meaning that it can only be accessed within the function in which it is declared. A regular variable, on the other hand, has local or global scope, depending on where it is declared.
void myFunction() {
static int staticVar = 0;
int regularVar = 0;
staticVar++;
regularVar++;
printf("Static variable: %dn", staticVar);
printf("Regular variable: %dn", regularVar);
}
int main() {
myFunction(); // Output: Static variable: 1 Regular variable: 1
myFunction(); // Output: Static variable: 2 Regular variable: 1
myFunction(); // Output: Static variable: 3 Regular variable: 1
return 0;
}
In this example, the myFunction() function contains a static variable named staticVar and a regular variable named regularVar. The staticVar variable is incremented on each function call and its value persists across function calls. The regularVar variable, on the other hand, is reinitialized to 0 on each function call and its value does not persist across function calls.
Initialization: A static variable is initialized only once, at the start of the program, and its value persists across function calls. A regular variable is initialized each time it is declared, either with an explicit value or with a default value of 0.
void myFunction() {
static int staticVar; // Initialized to 0
int regularVar; // Uninitialized
printf("Static variable: %dn", staticVar);
printf("Regular variable: %dn", regularVar);
}
int main() {
myFunction(); // Output: Static variable: 0 Regular variable: 135477232
myFunction(); // Output: Static variable: 0 Regular variable: 135477232
myFunction(); // Output: Static variable: 0 Regular variable: 135477232
return 0;
}
In this example, the myFunction() function contains a static variable named staticVar and a regular variable named regularVar. The staticVar variable is initialized to 0 only once, at the start of the program, while the regularVar variable is uninitialized and contains a garbage value on each function call.
Lifetime: A static variable has a lifetime that extends beyond the function in which it is declared, while a regular variable has a lifetime that is limited to the function in which it is declared.
int *myFunction() {
static int staticVar = 0;
int regularVar = 0;
staticVar++;
regularVar++;
printf("Static variable: %dn", staticVar);
printf("Regular variable: %dn", regularVar);
return &staticVar;
}
int main() {
int *ptr1 = myFunction(); // Output: Static variable: 1 Regular variable: 1
int *ptr2 = myFunction(); // Output: Static variable: 2 Regular variable: 1
printf("Static variable: %dn", *ptr1); // Output: Static variable: 2
printf("Static variable: %dn", *ptr2); // Output: Static variable: 2
return 0;
}