So why is it useful for C programmers to divide their programs into
separate--but cooperating--functions? Why not write every program as one big
``chunk'' of statements?
Think back again to the homework for the previous lesson, in which you found
the positions of a squatter's joints. In that program you used the built-in
sine and cosine functions.
Those functions were predefined for you, meaning that you didn't have to tell
the computer how to compute the sine and cosine of an angle. The work of
teaching the computer about sines and cosines had already been done for you.
And because that programming job had already been done, you could simply use
those functions in your own program, without worrying about how the sine and
cosine functions actually worked inside.
This example highlights the two most important reasons that C programmers use
The first reason is reusability. Once a function is defined, it can be
used over and over and over again. You can invoke the same function many times
in your program, which saves you work. Imagine what programming would be like
if you had to teach the computer about sines every time you needed to
find the sine of an angle! You'd never get your program finished!
Another aspect of reusability is that a single function can be used in several
different (and separate) programs. When you need to write a new program, you
can go back to your old programs, find the functions you need, and reuse those
functions in your new program. You can also reuse functions that somebody else
has written for you, such as the sine and cosine functions.
The second reason is abstraction. In order to use a particular function
you need to know the following things:
- The name of the function;
- What the function does;
- What arguments you must give to the function; and
- What kind of result the function returns.
But notice: If you just want to use the function in your program,
you don't have to know how it works inside! You don't have to understand
anything about what goes on inside the function.
It's sort of like driving a car or using a telephone. With an automobile, you
don't need to understand every detail about the engine and drive train and
wheels, if all you want to do is drive the car. Similarly, with a telephone,
you don't have to understand everything about the phone system in order to make
The only time you need to know how a function works inside is when you
need to write the function, or change how it works. (It's like a car again;
you need to know how a car works in order to build one or fix one.) But once a
function is written and working, you never need to look at its insides again.
Together, these two reasons make functions extremely useful--practically
essential!-for programmers who write large programs. The ability to
divide a program into abstract, reusable pieces is what makes it possible to
write large programs that actually work right.
Eric N. Eide
Department of Computer Science
University of Utah