Programming in C

(Barry) #1
Functions Calling Functions Calling... 135

If the function doesn’t take an argument, use the keyword voidbetween the paren-
theses. If the function doesn’t return a value, this fact can also be declared to thwart any
attempts at using the function as if it does:


void calculateTriangularNumber (int n);


If the function takes a variable number of arguments (such as is the case with printf
and scanf), the compiler must be informed.The declaration


int printf (char *format, ...);


tells the compiler that printftakes a character pointeras its first argument (more on that
later), and is followed by any number of additional arguments (the use of the ...).printf
and scanfare declared in the special file stdio.h.This is why you have been placing
the following line at the start of each of your programs:


#include <stdio.h>


Without this line, the compiler can assume printfand scanftake a fixed number of
arguments, which could result in incorrect code being generated.
The compiler automatically converts your arguments to the appropriate types when a
function is called, but only if you have placed the function’s definition or have declared
the function and its argument types before the call.
Here are some reminders and suggestions about functions:



  1. Remember that, by default, the compiler assumes that a function returns an int.

  2. When defining a function that returns an int, define it as such.

  3. When defining a function that doesn’t return a value, define it as void.

  4. The compiler converts your arguments to agree with the ones the function
    expects only if you have previously defined or declared the function.

  5. To play it safe, declare all functions in your program, even if they are defined
    before they are called. (You might decide later to move them somewhere else in
    your file or even to another file.)


Checking Function Arguments


The square root of a negative number takes you away from the realm of real numbers
and into the area of imaginary numbers. So what happens if you pass a negative number
to your squareRootfunction? The fact is, the Newton-Raphson process would never
converge; that is, the value of guesswould not get closer to the correct value of the
square root with each iteration of the loop.Therefore, the criteria set up for termination
of the whileloop would neverbe satisfied, and the program would enter an infinite loop.
Execution of the program would have to be abnormally terminated by typing in some
command or pressing a special key at the terminal (such as Ctrl+C).
Obviously, modifying the program to correctly account for this situation is called for
in this case.You could put the burden on the calling routine and mandate that it never

Free download pdf