Programming in C

(Barry) #1

124 Chapter 8 Working with Functions


Function Prototype Declaration


The function calculateTriangularNumberrequires a bit of explanation.The first line
of the function:
void calculateTriangularNumber (int n)
is called the function prototype declaration. It tells the compiler that
calculateTriangularNumberis a function that returns no value (the keyword void)
and that takes a single argument, called n,which is an int.The name that is chosen for
an argument, called its formal parameter name, as well as the name of the function itself,
can be any valid name formed by observing the rules outlined in Chapter 4, “Variables,
Data Types, and Arithmetic Expressions,” for forming variable names. For obvious rea-
sons, you should choose meaningful names.
After the formal parameter name has been defined, it can be used to refer to the
argument anywhere inside the body of the function.
The beginning of the function’s definition is indicated by the opening curly brace.
Because you want to calculate the nth triangular number, you have to set up a variable
to store the value of the triangular number as it is being calculated.You also need a vari-
able to act as your loop index.The variables triangularNumberand iare defined for
these purposes and are declared to be of type int.These variables are defined and initial-
ized in the same manner that you defined and initialized your variables inside the main
routine in previous programs.

Automatic Local Variables


Va r iables defined inside a function are known as automatic localvariables because they are
automatically “created” each time the function is called, and because their values are local
to the function.The value of a local variable can only be accessed by the function in
which the variable is defined. Its value cannot be accessed by any other function. If an
initial value is given to a variable inside a function, that initial value is assigned to the
variable eachtime the function is called.
When defining a local variable inside a function, it is more precise in C to use the
keyword autobefore the definition of the variable. An example of this is as follows:
auto int i, triangularNumber = 0;
Because the C compiler assumes by default that any variable defined inside a function is
an automatic local variable, the keyword autois seldom used, and for this reason it is not
used in this book.
Returning to the program example, after the local variables have been defined, the
function calculates the triangular number and displays the results at the terminal.The
closing brace then defines the end of the function.
Inside the mainroutine, the value 10 is passed as the argument in the first call to
calculateTriangularNumber.Execution is then transferred directly to the function
Free download pdf