Home »
Code Snippets »
C/C++ Code Snippets
C static variable in function example
By: IncludeHelp On 11 DEC 2016
Here, we will learn how a c static variable works in any function?
In this example we are declare a static variable var inside the function myFunction() and returning the value of var.
Function myFunction() is caling inside the main() function.
Let’s consider the program and output first
#include <stdio.h>
int myFunction()
{
static int var=0;
var+=1;
return var;
}
int main()
{
printf("var = %d\n",myFunction());
printf("var = %d\n",myFunction());
printf("var = %d\n",myFunction());
printf("var = %d\n",myFunction());
printf("var = %d\n",myFunction());
return 0;
}
Output
var = 1
var = 2
var = 3
var = 4
var = 5
Explanation
Static variable declared once but its scope is life time of the program, that’s why on every call of the function myFunction() value of var is increasing.
After removing the static from the declaration
Let’s consider the program and output
#include <stdio.h>
int myFunction()
{
int var=0;
var+=1;
return var;
}
int main()
{
printf("var = %d\n",myFunction());
printf("var = %d\n",myFunction());
printf("var = %d\n",myFunction());
printf("var = %d\n",myFunction());
printf("var = %d\n",myFunction());
return 0;
}
Output
var = 1
var = 1
var = 1
var = 1
var = 1
In the function myFunction() definition, var is not static, it’s a local/automatic variable here and it will be declared every time of program’s execution will move the function definition; that’s why on every calling of myFunction(), value of var will be 1.