๐งท static Keyword in C Language
Lifetime, Scope, and Data Hiding
๐น What is static in C?The static keyword in C is used to preserve the value of a variable and limit its scope. A static variable retains its value even after the function call ends.
๐ Uses of static in C
The static keyword is mainly used in:
- Static local variables
- Static global variables
- Static functions
1๏ธโฃ Static Local Variable
Definition:A static local variable is declared inside a function and retains its value between function calls.
Example:
#include <stdio.h>
void count() {
static int x = 0;
x++;
printf("%d ", x);
}
int main() {
count();
count();
count();
return 0;
}
1 2 3
๐ Normal local variables are destroyed after function execution, but static variables are not.
2๏ธโฃ Static Global Variable
Definition:A static global variable is declared outside all functions but cannot be accessed from other files.
Example:
#include <stdio.h>
static int num = 100;
int main() {
printf("%d", num);
return 0;
}
โ Scope limited to the same source file only.
3๏ธโฃ Static Function
Definition:A static function can be accessed only within the same file in which it is defined.
Example:
#include <stdio.h>
static void display() {
printf("Static Function");
}
int main() {
display();
return 0;
}
โ๏ธ Difference Between Static and Normal Variables
| Feature | Static Variable | Normal Variable |
|---|---|---|
| Lifetime | Entire program | Until block ends |
| Value retention | Yes | No |
| Memory | Allocated once | Allocated multiple times |
| Default value | 0 | Garbage value |
๐งช Example Showing Difference
#include <stdio.h>
void demo() {
int a = 1;
static int b = 1;
a++;
b++;
printf("a=%d b=%d\n", a, b);
}
int main() {
demo();
demo();
demo();
return 0;
}
a=2 b=2
a=2 b=3
a=2 b=4
๐ FAQs on static in C
Q1. Why use static variables?
To preserve variable values between function calls.
Q2. What is the default value of a static variable?
The default value is 0.
Q3. Can static variables be initialized?
Yes, but only once.
Q4. What is the scope of a static variable?
Inside function โ local scope
Outside function โ file scope
Q5. Can static functions be called from another file?
No, static functions have file-level scope.
๐ Key Points to Remember
- static increases variable lifetime
- Value is preserved between calls
- Improves data hiding
- Default value is zero