Occasionally, you may want a local variable to retain its value between function calls. The static keyword, introduced earlier as a means of limiting the visibility of external variables, also performs this task.
Summary: A static local variable retains its value through subsequent function calls.
If you precede a local variable declaration with static, the variable exists for the life of the program—the same lifetime as an external variable. The variable still has local visibility, however.
The STATIC.C program below shows how to create and use a static local variable. In STATIC.C, the value of the methuselah variable persists through all calls to the add_val function, which adds values to methuselah and prints the variable's value.
/* STATIC.C: Demonstrate static variables. */
#include <stdio.h>
void add_val( int value );
main()
{
add_val( 1 );
add_val( 5 );
add_val( 20 );
}
void add_val( int value )
{
static int methuselah;
if( value == 1 )
methuselah = 0;
methuselah = methuselah + value;
printf( "methuselah = %d\n", methuselah );
}
The add_val function in STATIC.C accepts one parameter and also declares a static local variable named methuselah. Each time add_val is called, it adds the passed value to methuselah.
The main function calls the add_val function three times, passing the values 1, 5, and 20 to add_val as arguments. The program's output
methuselah = 1
methuselah = 6
methuselah = 26
shows that the value of methuselah persists through all three function calls.
If we remove the static keyword from the declaration of methuselah,
the variable's value is not preserved between function calls. The value of
methuselah is unpredictable the second and third times that add_val
is called.
Notice that extending a local variable's lifetime with static doesn't affect its visibility. The methuselah variable keeps its value between function calls, but you can't refer to the variable outside the add_val function.