Skip to main content

Static variables in C

Static Variables

  • A static variable is declared using the keyword static such that the storage is allocated only one time and is used for the entirety of the program.

  • Their value is retained across multiple function calls and is preserved even after the function that declared the variable has completed execution.

Static Variables - Example

#include <stdio.h>

void increment()
{
static int count = 0;
count++;
printf("count = %d\n", count);
}

int main()
{
increment();
increment();
increment();
return 0;
}
Output:

Example

The count variable is declared as static inside the increment function. When this function is called, the value of count is incremented and printed.

The output of this code will be:

count = 1
count = 2
count = 3

This demonstrates that the value of count is retained even after the function call has completed.

visibility

Static variables are only visible within the function in which they are declared. They are not accessible outside of that function.