Static Storage Class in C
'static' storage class in C
The static storage class is used to declare variables or functions with static
duration.
- Static variables within a function are only initialized once and retain their values between function calls, making them useful for lets say - counting the number of times the function has been called.
- Syntax for declaring a static variable:
static data_type variable_name;
Use of static
storage class
The static storage class in C can be used for both variables and functions.
static
storage class for Variables
For variables, the static
keyword is used to declare a variable with static storage duration, meaning the variable retains its value across multiple function calls and is only visible within the same function.
Here's an example of using a static
variable to keep track of the number of times a function has been called:
#include <stdio.h>
void count()
{
static int c = 0;
c++;
printf("count = %d\n", c);
}
int main()
{
for (int i = 0; i < 5; i++)
{
count();
}
return 0;
}
Output:
Output:
count = 1
count = 2
count = 3
count = 4
count = 5
Explanation
The variable c
retains its value across multiple calls to the count() function, allowing it to keep track of the number of times the function has been called.
static
storage class for Functions
The static storage class in C can also be used for functions. When a function is declared as static, it has internal linkage, meaning it can only be called within the same translation unit (file) in which it is defined.
Syntax for declaring a static function:
static return_type function_name (parameters) {
// function body
}
Here's an example of using the static storage class for a function:
#include <stdio.h>
static void myFunction()
{
printf("This is a static function.\n");
}
int main()
{
myFunction();
return 0;
}
Output:
Output:
This is a static function.
Explanation
The function myFunction()
is declared as static, so it can only be called within the same file (main.c) in which it is defined.
The static
storage class in C is used to declare variables or functions with static
duration, retaining their value across multiple function calls. Static variables have internal linkage, accessible only within the same function. Functions declared as static can only be called within the same file.