# More on interface

February 2020

Back to index.html.

# More on interface

## Use of the interface statement

We have seen that interface provides a template of the external procedure. It is relevant to remove the risk of mismatch between given arguments and assumed arguments. The interface statement has some more useful usage, especially combined with a module.

• To define an alternative name of a procedure.
• To define a generic procedure which unifies several procedures with different types of arguments into a single procedure.
• To define user-defined operator, which directly calls a procedure.

We are looking at the first 2 features in this chapter.

## Alternative name

You can put another name on a procedure using interface. We have the following subroutine for the factorial of an integer $n$, and we put it into a module.

module math
implicit none

contains
function intfactorial(n) result(f)
integer,intent(in) :: n
integer :: i
integer :: f
f = 1
do i=1,n
f = f * i
end do
end function intfactorial
end module math

If you feel the name intfactorial awkward, you can put an alternative name (say, fact) in the interface statement inside the module.

module math
implicit none
interface fact
module procedure intfactorial
end interface fact
...
end module math

In this way, using this module, you can call the same function as either fact and intfactorial.

## Generic name of procedure

We can generalize the naming feature to give a common name to different procedures. For example, we have another function to calculate the factorial, but it returns a real number (not integer). We assume that the argument is also real.

module math
implicit none

contains
function intfactorial(n) result(f)
integer,intent(in) :: n
integer :: i
integer :: f
f = 1
do i=1,n
f = f * i
end do
end function intfactorial

function realfactorial(n) result(f)
real,intent(in) :: n
integer :: i
real :: f
f = 1
do i=1,n
f = f * i
end do
end function realfactorial
end module math

It is inconvenient for the programmer to choose the appropriate function manually. Instead, once you put a common generic name to the both functions, you just call the function using the generic name, and the program automatically choose the appropriate one.

module math
implicit none
interface fact
module procedure intfactorial realfactorial
end interface fact
...
end module math

For example, in the main program, the function can be called with the generic name.

   ! integer argument = calling intfactorial
print *,fact(5)

! real argument = calling realfactorial
print *,fact(5.0)

The decision of which function is chosen is determined when the program compiles. If there is no appropriate function to meet the types of arguments, the compilation fails with an error.

Back to index.html.