Frequently Asked C Language Interview Question & Answers
What are static variables in C?
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 Count is 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.