C program to illustrate the concept of static variables


Static variables are the special type of variables. These variables retain their value throughout the program but they can be accessed only within the block in which they are defined.

 C program to illustrate the concept of static variables


Source code:

#include<stdio.h>
int main()
{
	void show(void);
	printf("\n First Call of show()");   
	show();                              //Step 1
	printf("\n Second Call of show()");
	show();                              //Step 2
	printf("\n Third Call of show()");
	show();                             //Step 3
	return 0;
}


void show(void)
{
	static int i;           
	printf("\n i=%d",i); 
	i++;
}


edit-code-image

Sample test cases:

First Call of show()
i=0
Second Call of show()
i=1
Third Call of show()
i=2

Explanation:

Step 1: The function show() is called from the main program for the first time. In first call of function show() the static variable is created which holds zero by default
and then incremented.
Step 2: The function show() is called for the second time. In second call of function show() the static variable value is displayed.
Step 3: The function show() is called for the third time. In third call of function show() the static variable value is displayed. The value gets incremented will be 2 since static variables are capable of retaining their value between function calls.

More Content :Explore More
More about static content : Static Variable