w3resource

What is a static variable in C?

C - Static Variables

In C programming language static is a reserved word controlling both lifetime (as a static variable) and visibility (depending on linkage).

You can declare variables (or functions) at the top level (that is, not inside a function) to be static; such variables are visible (global) to the current source file (but not other source files). This gives an unfortunate double meaning to static; this second meaning is known as static linkage. Two functions or variables having static linkage in separate files are entirely separate; neither is visible outside the file in which it is declared.

Following program uses a function called test() to sum integers. The function uses a static variable to store the cumulative sum.

Example: Static Variables

#include <stdio.h>

int main()
{
   int i;
    for (i = 0; i < 5; ++i)
        test();
}
void test()
{
    static int stat_var = 10;
    int x = 100;
    stat_var += 50;
	x += 50;
	printf("x = %d, stat_var = %d\n", x, stat_var);
}

Output:

x = 150, stat_var = 60
x = 150, stat_var = 110
x = 150, stat_var = 160
x = 150, stat_var = 210
x = 150, stat_var = 260

While the static variable, stat_var, would be automatically initialized to zero, it is preferable to do so explicitly. In any case, the initialization is performed only once at the time of memory allocation by the compiler. During the execution of a program, the variable stat_var retains its value. The stat_var is incremented each time function test() is called.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/c-snippets/what-is-static-variable-in-c.php