In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime(or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is stack allocated and deallocated on the call stack; and in contrast to objects, whose storage is dynamically allocatedand deallocated in heap memory.

An example of static local variable in C:

#include <stdio.h>

void func();

int main() { //int argc, char *argv[] inside the main is optional in the particular program
	func(); // prints 1
	func(); // prints 2
	func(); // prints 3
	func(); // prints 4
	func(); // prints 5
	return 0;
}
void func() {
	static int x = 0; 
	/* x is initialized only once across five calls of func() and
	  the variable will get incremented five 
	  times after these calls. The final value of x will be 5. */
	x++;
	printf("%d\n", x); // outputs the value of x
}

You have no rights to post comments