Statics in functions
It is sometimes useful to be able to declare a variable within a function
which keeps its value between calls. Such variables are called statics in
C. They can still only be accessed within the function where they are
declared (they have local scope), but there is only one version of the
variable and all instances of the function refer to it. Statics are,
therefore, not kept in the block instance of the function and are not part
of the stack used to allocate automatic variables. The keyword static is
used at the front of their declaration, e.g.
static int ival1, ival2;
static char str[12];
The important use for statics is to allow a value to be remembered between
calls, without allowing it to be accessed by other functions.
Example using statics
#include <stdio.h>
int Static_Demo(int Init) {
static int Hidden;
if (Init==0) Hidden = Init; else Hidden++;
if (Hidden<3) return Init;
return Hidden;
}
void main() {
printf("%d\n",Static_Demo(0));
printf("%d\n",Static_Demo(1));
printf("%d\n",Static_Demo(2));
printf("%d\n",Static_Demo(3));
printf("%d\n",Static_Demo(4));
printf("%d\n",Static_Demo(1));
}
Plain text version to compile.
Exercises on this section.
Next - Global items.
Back to Contents page.