FunctionX - Practical Learning Logo

Static Variables



The static keyword allows a variable to maintain its value among different function calls. If the value of a static variable changes when the variable has been accessed, the variable keeps the new value. If the same variable gets accessed again, it would be holding its most recent value. This is possible because, when the static variable is declared, the compiler uses a separate memory area to store it. By doing this, when the value of the static variable gets changed, it is updated in the memory it is occupying. And because this memory is separate, the compiler can monitor its values even when its function exits.

To declare a variable as static, type the static keyword to its left. Here is an example:

void Example(){	static int Mine;}

You can declare as many static variables as you judge necessary, and you can use the same name for different static variables in different functions:

void Example(){	static int Mine;}void Function(){	static int Mine;}

Copyright © 2003-2005 FunctionX, Inc.