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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join