Static Variables in C : A Step-by-Step Guide to Retaining Values Across Function Calls


In C programming, a static variable is a variable that retains its value between function calls. It is initialized only once and its value persists across function calls, unlike local variables which are re-initialized with each function call. Static variables are typically used to maintain a value that must be retained across multiple function calls, but that should not be accessible from outside the function.

The basic syntax for declaring a static variable in C is as follows:

           static data_type variable_name;

Here, the data_type specifies the data type of the variable, and the variable_name is the name of the variable. The static keyword is used before the data type to indicate that the variable is a static variable.

Here is an example of a static variable being used in a function:

  • The function display declares a static variable number which is initialized with the value 1. Every time the function is called, it increments the value of number by 2 and prints its value.
  • In the main function, the display function is called three times, and each time, the value of number is incremented and printed. As the variable is static, the value of the variable is retained between function calls and the final value of number is 4.
  • This program demonstrates how to declare and use a static variable within a function, how static variables retain their value across function calls, and how they can be used to maintain state across multiple function calls.

Source Code

//Static Variable
 
#include<stdio.h>
 
void display();
 
 
int main()
{
    display();
    display();
    display();
}
 
void display()
{
    static int x=1;
    x++;
    printf("\nx : %d",x);
}
 
To download raw file Click Here

Output

x : 2
x : 3
x : 4

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C