158 Chapter 8 Working with Functions
int i;
void auto_static (void);
for ( i = 0; i < 5; ++i )
auto_static ();
return 0;
}
Program 8.15 Output
automatic = 1, static = 1
automatic = 1, static = 2
automatic = 1, static = 3
automatic = 1, static = 4
automatic = 1, static = 5
Inside the auto_staticfunction, two local variables are declared.The first variable,
called autoVar, is an automaticvariable of type intwith an initial value of 1 .The sec-
ond variable, called staticVar, is a static variable, also of type intand also with an ini-
tial value of 1 .The function calls the printfroutine to display the values of these two
variables. After this, the variables are each incremented by 1 , and execution of the func-
tion is then complete.
The mainroutine sets up a loop to call the auto_staticfunction five times.The
output from Program 8.15 points out the difference between the two variable types.The
value of the automaticvariable is listed as 1 for each line of the display.This is because
its value is set to 1 each time the function is called. On the other hand, the output shows
the value of the static variable steadily increasing from 1 through 5 .This is because its
value is set equal to 1 only once—when program execution begins—and because its
value is retained from one function call to the next.
The choice of whether to use a static variable or automatic variable depends upon
the intended use of the variable. If you want the variable to retain its value from one
function call to the next (for example, consider a function that counts the number of
times that it is called), use a static variable. Also, if your function uses a variable whose
value is set once and then never changes, you might want to declare the variable static, as
it saves the inefficiency of having the variable reinitialized each time that the function is
called.This efficiency consideration is even more important when dealing with arrays.
From the other direction, if the value of a local variable must be initialized at the
beginning of each function call, an automatic variable seems the logical choice.
Program 8.15 Continued