|
|
Keep a count on the # times that a function was invoked:
#include <stdio.h>
void f( )
{
int i = 0; // Normal local
static int j = 0; // Static local
i++;
j++;
printf( "i = %d, j = %d\n", i, j );
}
int main( int argc, char* argv[] )
{
f();
f();
f();
}
|
The static local variable j will keep the count !
|
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
When we change the variable y 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 !
|
The main( ) function
cannot
access the
variable x !!! (compile error)
DEMO:
/home/cs255001/demo/tmp/demo.c + demo2.c
Usage: static global can limit to search for erroneous to the program file that contains the static global variable