ADVERTISEMENT
ADVERTISEMENT

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.

ADVERTISEMENT

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.


COMMENTS

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.