Fortunately, there is a mechanism in C that gets around this conundrum. It is the
keyword
static
.
When you use the keyword
static
in front of a variable declaration in a
function, it has the effect of initializing the variable only the first time that the function is
run. Perfect! That’s just what is required in this situation. We can keep our variable in the
function where it’s used without it getting set back to 0 every time the function runs.
Sketch 4-04 shows this in operation:
Return Values
Computer science,
as an academic discipline, has as its parents mathematics and
engineering. This heritage lingers on in many of the names associated with programming.
The word
function
is itself a mathematical term. In mathematics, the input to the function
(the argument) completely determines the output. We have written functions that take an
input, but none that give us back a value. All our functions have been “void” functions. If
a function returns a value, then you specify a return type.
Let’s look at writing a function that takes a temperature
in degrees Centigrade and
returns the equivalent in degrees Fahrenheit:
The function definition now starts with
int
rather than
void
to
indicate that the function
will return an
Dostları ilə paylaş: