130 Chapter 8 Working with Functions
Program 8.7 Output
result = 15.50
f1 = -15.50
result = 25.00
result = 716.00
result = 716.00
1.50
The absoluteValuefunction is relatively straightforward.The formal parameter called x
is tested against zero. If it is less than zero, the value is negated to take its absolute value.
The result is then returned back to the calling routine with an appropriate returnstate-
ment.
You should note some interesting points with respect to the mainroutine that tests
out the absoluteValuefunction. In the first call to the function, the value of the vari-
able f1, initially set to –15.5, is passed. Inside the function itself, this value is assigned to
the variable x. Because the result of the iftest is TRUE, the statement that negates the
val ue of xis executed, thereby setting the value of xto 15.5. In the next statement, the
val ue of xis returned to the mainroutine where it is assigned to the variable resultand
is then displayed.
When the value of xis changed inside the absoluteValuefunction, this in no way
affects the value of the variable f1.When f1was passed to the absoluteValuefunction,
its value was automatically copiedinto the formal parameter xby the system.Therefore, any
changes made to the value of xinside the function affect only the value of xand not the
val ue of f1.This is verified by the second printfcall, which displays the unchanged
val ue of f1at the terminal. Make certain you understand that it’s not possible for a func-
tion to directly change the value of any of its arguments—it can only change copies of
them.
The next two calls to the absoluteValuefunction illustrate how the result returned
by a function can be used in an arithmetic expression.The absolute value of f2is added
to the absolute value of f3and the sum is assigned to the variable result.
The fourth call to the absoluteValuefunction introduces the notion that the type of
argument that is passed to a function should agree with the type of argument as declared
inside the function. Because the function absoluteValueexpects a floating value as its
argument, the integer variable i1is first cast to type floatbefore the call is made. If you
omit the cast operation, the compiler does it for you anyway because it knows the
absoluteValuefunction is expecting a floating argument. (This is verified by the fifth
call to the absoluteValuefunction.) However, it’s clearer what’s going on if you do the
casting yourself rather than relying on the system to do the conversion for you.
The final call to the absoluteValuefunction shows that the rules for evaluation of
arithmetic expressions also pertain to values returned by functions. Because the value
returned by the absoluteValuefunction is declared to be of type float, the compiler
treats the division operation as the division of a floating-point number by an integer. As
you recall, if one operand of a term is of type float, the operation is performed using