Help!
Next: Why Functions?
Up: Functions
Previous: Built-in Functions

A Simple Function

You do not have to write many programs before you realize that you would like to use a function that is not provided by C. Fortunately, it is possible to define and use your own functions. In this section we will look at a simple example of doing just that.

Take a look at ``user1.c'' (or view it directly).

Whereas C provides a function named ``log10'' to compute base ten logarithms, it provides no corresponding function for base two. Because of this, we are using the log10 function to compute the base two logarithm according to a standard mathematical formula.

In what ways would our program be simplified if there were a standard function, say LOG2, to compute base two logarithms?

Click here for answer

We can't change C. But we can define, once and for all, our own LOG2 function that can be used almost exactly like an intrinsic function such as log10. This allows us to write down the definition once and then call it in as many places as we want without having to use the error-prone technique of duplicating the same code fragment over and over.

And best of all, it's not very hard to do.

Now look at ``user2.c'' (or view it directly). It is a different version of the last program. Experiment with running this version.


Help!
Next: Why Functions?
Up: Functions
Previous: Built-in Functions

Hamlet Project
hamlet@cs.utah.edu