What are static variables in C ?

devquora
devquora

Posted On: Feb 22, 2018

 

C defines another class of variables called static variables. Static variables are of two types:

    • Static variables that are declared within a function (function static variables). These variables retain their values from the previous call, i.e., the values which they had before returning from the function.
    • File static variables. These variables are declared outside any function using the keyword static. File static variables are accessible only in the file in which they are declared. This case arises when multiple files are used to generate one executable code.
#include <stdio.h>
void PrintCount()
{
 static int Count = 1;
 //Count is initialized only on the first call
 printf( "Count = %d\n", Count);
 Count = Count + 1;
 //The incremented value of Count is retained
}
int main()
{
 PrintCount();
 PrintCount();
 PrintCount();
 return 0;
}
OutPut:
Count = 1
Count = 2
Count = 3

The output of the program is a sequence of numbers starting with 1, rather than a string of 1′s. The initialization of static variable Countis performed only at the first instance of the function call. In successive calls to the function, the variable count retains its previous value. However, these static variables are not accessible from other parts of the program.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    C programming interview questions

    What is a scope resolution operator in C ?

    The scope resolution operator (::) is useful in C programming when both global and local variables have the same name,..

    C programming interview questions

    What is register variable in C language ?

    C language allows the use of the prefix register in primitive variable declarations. Such variables are called register..

    C programming interview questions

    What is a structure in C Language.How to initialise a structure in C?

    A structure is a composite data type declaration that defines a physically grouped list of variables to be placed under..