|
|
Keep a count on the # times that a function was invoked:
#include <stdio.h> void f( ) { static int j = 0; // Static local j++; printf("# times f( ) called: %d\n", j); .... // Body of f( ) omitted } int main( int argc, char* argv[] ) { f(); f(); f(); } |
DEMO: demo/C/set1/static-local.c
The static local variable j will keep a count on the number of times that f( ) was invoked
|
Consider: a previous example on global variables in 2 program files:
progFile1.c | progFile2.c |
---|---|
#include <stdio.h>
extern int x, y;
int main( int argc, char* argv[] )
{
f( );
printf( "%d %d\n", x, y );
}
|
int x;
int y = 4;
int f( )
{
x = y + 3;
}
|
The main( ) function
can
access the
global variables
DEMO:
/home/cs255001/demo/C/set1/static-glob1.c +
static-glob2.c
When we change the variable x into a static global:
progFile1.c | progFile2.c |
---|---|
#include <stdio.h>
extern int x, y;
int main( int argc, char* argv[] )
{
f( );
printf( "%d %d\n", x, y );
}
|
static int x; int y = 4; int f( ) { x = y + 3; } // Bugs related to x must be // in functions in this file ! // because x is static global |
The main( ) function
cannot
access the
static
variable x !!! (compile error)
DEMO:
/home/cs255001/demo/C/set1/static-glob1.c +
static-glob2.c
Usage:
static global can
limit the
search for bugs
to the
program file that
contains the static
global variable
Because
functions in
other program files
cannot
access the
static global
variables !