Programming in C

(Barry) #1

156 Chapter 8 Working with Functions


So remember that while global variables have default initial values of zero, local vari-
ables have no default initial value and so must be explicitly initialized by the program.

Automatic and Static Variables


When you normally declare a local variable inside a function, as in the declaration of the
variables guessand epsilonin your squareRootfunction
float squareRoot (float x)
{
const float epsilon = .00001;
float guess = 1.0;

...
}
you are declaring automaticlocal variables. Recall that the keyword autocan, in fact, pre-
cede the declaration of such variables, but is optional because it is the default case. An
automatic variable is, in a sense, actually created each time the function is called. In the
preceding example, the local variables epsilonand guessare created whenever the
squareRootfunction is called. As soon as the squareRootfunction is finished, these
local variables “disappear.”This process happens automatically, hence the name automatic
variables.
Automatic local variables can be given initial values, as is done with the values of
epsilonand guess,previously. In fact, any valid C expression can be specified as the ini-
tial value for a simple automatic variable.The value of the expression is calculated and
assigned to the automatic local variable eachtime the function is called.^4 And because an
automatic variable disappears after the function completes execution, the value of that
variable disappears along with it. In other words, the value an automatic variable has
when a function finishes execution is guaranteednot to exist the next time the function is
called.
If you place the word staticin front of a variable declaration, you are in an entirely
new ball game.The word staticin C refers not to an electric charge, but rather to the
notion of something that has no movement.This is the key to the concept of a static
variable—it does notcome and go as the function is called and returns.This implies that
the value a static variable has upon leaving a function is the same value that variable will
have the next time the function is called.
Static variables also differ with respect to their initialization. A static, local variable is
initialized only onceat the start of overall program execution—and not each time that
the function is called. Furthermore, the initial value specified for a static variable mustbe
a simple constant or constant expression. Static variables also have default initial values of
zero, unlike automatic variables, which have no default initial value.
In the function auto_static, which is defined as follows:
4. In the case of constvariables, they can be stored in read-only memory. So they may not be
initialized each time the function is entered.

Free download pdf