136 Chapter 8 Working with Functions
pass a negative argument to the squareRootfunction. Although this approach might
seem reasonable, it does have its drawbacks. Eventually, you would develop a program
that used the squareRootfunction but which forgot to check the argument before call-
ing the function. If a negative number were then passed to the function, the program
would go into an infinite loop as described and would have to be aborted.
A much wiser and safer solution to the problem is to place the onus of checking the
value of the argument on the squareRootfunction itself. In that way, the function is
“protected” from anyprogram that used it. A reasonable approach to take is to check the
value of the argument xinside the function and then (optionally) display a message if the
argument is negative.The function can then immediately return without performing its
calculations. As an indication to the calling routine that the squareRootfunction did not
work as expected, a value not normally returned by the function could be returned.^1
The following is a modified squareRootfunction, which tests the value of its argu-
ment and which also includes a prototype declaration for the absoluteValuefunction as
described in the previous section.
/* Function to compute the square root of a number.
If a negative argument is passed, then a message
is displayed and -1.0 is returned. */
float squareRoot (float x)
{
const float epsilon = .00001;
float guess = 1.0;
float absoluteValue (float x);
if ( x < 0 )
{
printf ("Negative argument to squareRoot.\n");
return -1.0;
}
while ( absoluteValue (guess * guess - x) >= epsilon )
guess = ( x / guess + guess ) / 2.0;
return guess;
}
If a negative argument is passed to the preceding function, an appropriate message is dis-
played, and the value –1.0is immediately returned to the calling routine. If the argu-
ment is not negative, calculation of the square root proceeds as previously described.
1.The square root routine in the standard C library is called sqrtand it returns a domain errorif a
negative argument is supplied.The actual value that is returned is implementation-defined. On
some systems, if you try to display such a value, it displays as nan, which means not a number.