Programming in C

(Barry) #1
Functions and Arrays 137

As you can see from the modified squareRootfunction (and as you also saw in the
last example from Chapter 7, “Working with Arrays”), you can have more than one
returnstatement in a function.Whenever a returnis executed, control is immediately
sent back to the calling function; any program statements in the function that appear
after the returnare not executed.This fact also makes the returnstatement ideal for
use by a function that does not return a value. In such a case, as noted earlier in this
chapter, the returnstatement takes the simpler form


return;


because no value is to be returned. Obviously, if the function issupposed to return a
value, this form cannot be used to return from the function.


Top-Down Programming


The notion of functions that call functions that in turn call functions, and so on, forms
the basis for producing good, structured programs. In the mainroutine of Program 8.8,
the squareRootfunction is called several times. All the details concerned with the actual
calculation of the square root are contained within the squareRootfunction itself, and
not within main.Thus, you can write a call to this function before you even write the
instructions of the function itself, as long as you specify the arguments that the function
takes and the value that it returns.
Later, when proceeding to write the code for the squareRootfunction, this same
type of top-down programmingtechnique can be applied:You can write a call to the
absoluteValuefunction without concerning yourself at that time with the details of
operation of that function. All you need to know is that you candevelop a function to
take the absolute value of a number.
The same programming technique that makes programs easier to write also makes
them easier to read.Thus, the reader of Program 8.8 can easily determine upon exami-
nation of the mainroutine that the program is simply calculating and displaying the
square root of three numbers. She need not sift through all of the details of how the
square root is actually calculated to glean this information. If she wants to get more
involved in the details, she can study the specific code associated with the squareRoot
function. Inside that function, the same discussion applies to the absoluteValuefunc-
tion. She does not need to know how the absolute value of a number is calculated to
understand the operation of the squareRootfunction. Such details are relegated to the
absoluteValuefunction itself, which can be studied if a more detailed knowledge of its
operation is desired.


Functions and Arrays


As with ordinary variables and values, it is also possible to pass the value of an array ele-
ment and even an entire array as an argument to a function.To pass a single array ele-
ment to a function (which is what you did in Chapter 7 when you used the printf

Free download pdf