Next: How Functions Work
Up: Functions
Previous: Intrinsic Functions

User Defined Functions

You will not have to write many programs before you realize that you would like to use a function that is not provided as an intrinsic by Fortran. Fortunately, it is possible to define and use your own functions. In this section we will explore how to do that.

Let's begin by considering ``user1.f'' (or view it directly).

Try running the program a few times. This program reads in three real numbers and prints out their base two logarithms.

Whereas Fortran provides an intrinsic function LOG10 to compute base ten logarithms, it provides no corresponding function for base two. Because of this, we are using the LOG10 intrinsic to compute the base two logarithm according to a standard mathematical formula.

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

Click here for answer

We can't change Fortran. 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 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.f'' (or view it directly). It is a different version of the last program.

The program now consists of an implementation of a LOG2 function followed by the main program.

Let's look first at the main program (which begins with the keyword PROGRAM). There is one (and only one) clue that tells us that LOG2 is not an intrinsic function. What is it?

Click here for the answer

Now look at the beginning of the file, where our LOG2 function is implemented. Take a look at the code and see if you can figure out all the ways in which a function differs from a main program.

Click here for the answer


Next: How Functions Work
Up: Functions
Previous: Intrinsic Functions

Hamlet Project
hamlet@cs.utah.edu