Static Storage Class in C Programming

This is a storage class for global variables. That is, it will have scope in the block or function in which it is defined as well in the calling/called functions too. In other words, the value stored in this type of variable will not be re-initialized to zero or null when it comes back to the function where it is defined. A keyword static is used before declaring the variable. It can be declared outside the block or function that is using this variable or within the block or function in which it is being used. No matter wherever it is declared, it is automatically initialized to zero at the beginning of program execution. Then its value remain same, incremented or decremented (depending upon the operations performed on it) throughout the function irrespective of how much ever times the function is being called. These types of variables are stored in the RAM memory. Hence they will have memory address.

#include <stdio.h>
static  int intTotal; //initialized to zero

void calcTotal();
void main(){ 
	printf("\nValue at intTotal before initializing is %d ", intTotal

	intTotal = 100;
	printf("\nValue at intTotal after initializing is %d ", intTotal);

	calcTotal();
	printf("\nValue at intTotal after calling the function is %d ", intTotal);

	calcTotal();
	printf("\nValue at intTotal after the 2nd call to function is %d ", intTotal);
}

void calcTotal(){
	intTotal += 10;
}

This program illustrates how static value of variable is changed throughout the life of the program. Here we can notice that intTotal is initialized to zero as soon as it is declared. It keeps its previous value throughout the program. When the function calcTotal is called, it retains its value as 100 and is used in the function to get it incremented by 10. When the function control comes back to the main function, its value is not lost and still keeps it as 110 and prints it. Same is observed when second time function calcTotal is called. Hence we can say, static variable act as a global variable throughout the program. Its scope is not vanished after its use in any of the function.

Translate ยป