What is the use of the static keyword in C?
A static local variable is created once and keeps its value between function calls. A static global variable or function is visible only in its own file.
#include <stdio.h>
void count(void) {
static int n = 0;
n++;
printf("%d ", n);
}
int main(void) {
count(); count(); count();
printf("\n");
return 0;
}
Output:
Output of the above program is
1 2 3
A normal local variable would print 1 every time.
Learn more about the similar topics:
| Tutorials |
|---|
| C Functions |
| C Function Arguments and Return Value |
| C Call by Value and Call by Reference |
| C Recursion |
| C Scope and Storage Classes |
| Exercises & Assignments |
|---|
| Write a C program to find the factorial of a number using recursion |
| Write a C program to swap two numbers using a function and pointers |