Fortran

Guide To Learn

Redefining built-in operators

To wrap up the chapter, in this section we’ll practice redefining Fortran’s built-in operators to do something more or other than originally intended. For example, this could involve either of the following:

  • Performing the same operation, but operating on custom types –For example, we could define the arithmetic addition operation (+) for the derived type Person from the derived type. Depending on the application, the result of adding two instances of Person type either could be an instance of some new type–for example, People or Team–or could yield an array of Person instances.
  • Modifying the intended operation –For example, you could redefine the addition operator so it doesn’t add numbers but instead multiplies them.

I leave this one as an exercise for you (“Exercise 2” sidebar). It’s a fairly new concept, but we’ve already covered all the pieces you’ll need, and it’s a matter of putting them together in the correct order.

Exercise 2: Defining a new string concatenation operator

The way we concatenate strings in Fortran is with the // operator. Coming from Python, where it’s done with the + operator, it may be convenient to be able to do the same in Fortran. Implement the + operator so that you can concatenate Fortran strings with it:

print *, 'Hello' + ' world!'

should print Hello world! to the screen.

You can find the solution to this exercise in the “Answer key” section near the end of this chapter.

Redefining built-in operators

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top