Programming in C

(Barry) #1

128 Chapter 8 Working with Functions


After the value of the greatest common divisor has been calculated by the gcdfunction,
the statement
return u;
is executed.This has the effect of returning the value of u,which is the value of the
greatest common divisor, back to the calling routine.
You might be wondering what you can do with the value that is returned to the call-
ing routine. As you can see from the mainroutine, in the first two cases, the value that is
returned is stored in the variable result. More precisely, the statement
result = gcd (150, 35);
says to call the function gcdwith the arguments 150 and 35 and to store the value that
is returned by this function in the variable result.
The result that is returned by a function does not have to be assigned to a variable, as
you can see by the last statement in the mainroutine. In this case, the result returned by
the call
gcd (83, 240)
is passed directly to the printffunction, where its value is displayed.
A C function can only return a single value in the manner just described. Unlike
some other languages, C makes no distinction between subroutines (procedures) and
functions. In C, there is only the function, which can optionally return a value. If the
declaration of the type returned by a function is omitted, the C compiler assumes that
the function returns an int—if it returns a value at all. Some C programmers take
advantage of the fact that functions are assumed to return an intby default and omit
the return type declaration.This is poor programming practice and should be avoided.
When a function returns a value, make certain you declare the type of value returned in
the function’s header, if only for the sake of improving the program’s readability. In this
manner, you can always identify from the function header not only the function’s name
and the number and type of its arguments, but also if it returns a value and the returned
value’s type.
As noted earlier, a function declaration that is preceded by the keyword voidexplicit-
ly informs the compiler that the function does not return a value. A subsequent attempt
at using the function in an expression, as if a value were returned, results in a compiler
error message. For example, because the calculateTriangularNumberfunction of
Program 8.4 did not return a value, you placed the keyword voidbefore its name when
defining the function. Subsequently attempting to use this function as if it returned a
value, as in
number = calculateTriangularNumber (20);
results in a compiler error.
In a sense, the voiddata type is actually defining the absenceof a data type.Therefore,
a function declared to be of type voidhas no value and cannot be used as if it does have
a value in an expression.
Free download pdf