What is static keyword in C: Explanation and Examples
static keyword changes the lifetime and visibility of variables and functions. It makes variables keep their value between function calls and limits the scope of functions or variables to the file they are declared in.How It Works
The static keyword in C controls two main things: how long a variable lives and where it can be seen (its scope). Normally, variables inside a function are created when the function runs and destroyed when it ends. But if you add static, the variable stays alive for the whole program run, remembering its value between calls.
Think of it like a bookmark in a book. Without static, every time you open the book (call the function), you start fresh at page one. With static, you keep your place and continue from where you left off.
Also, when static is used outside functions, it hides the variable or function from other files. It’s like keeping a tool in your personal toolbox instead of sharing it with everyone.
Example
This example shows a static variable inside a function that remembers how many times it was called.
#include <stdio.h> void countCalls() { static int count = 0; // This variable keeps its value count++; printf("Function called %d times\n", count); } int main() { countCalls(); countCalls(); countCalls(); return 0; }
When to Use
Use static when you want a variable to keep its value between function calls without making it global. This is useful for counters, flags, or caching results inside functions.
Also, use static for functions or variables in a file to hide them from other files. This helps avoid name conflicts and keeps your code organized, like keeping private notes in a diary.
Key Points
- Static variables inside functions keep their value between calls.
- Static variables outside functions have file scope, hidden from other files.
- Static functions are only visible within the file they are declared in.
- Helps manage data lifetime and avoid naming conflicts.