The use of keyword and default arguments is not just as simple as it appears in the Appendix 3, section 6 program units, where an explicit interface is required. Therefore, we give a complete example here. The formal parameters of the interface are used as keywords. They need not be the same names as in the actual subprogram. They are not specified in the calling program unit.
IMPLICIT NONE INTERFACE SUBROUTINE SOLVE (A, B, N) INTEGER, INTENT (IN) :: N REAL, INTENT(OUT) :: A REAL, INTENT(IN), OPTIONAL :: B END SUBROUTINE SOLVE END INTERFACE REAL X ! Note that A, B and N are not specified as REAL ! or INTEGER in this unit. CALL SOLVE(B=10.0,N=50,A=X) WRITE(*,*) X CALL SOLVE(B=10.0,N=100,A=X) WRITE(*,*) X CALL SOLVE(N=100,A=X) WRITE(*,*) X END SUBROUTINE SOLVE(A, B, N) REAL, OPTIONAL, INTENT (IN) :: B IF (PRESENT(B)) THEN TEMP_B = B ELSE TEMP_B = 20.0 END IF A = TEMP_B + N RETURN ENDNote that the statement IMPLICIT NONE in the main program does not transfer automatically to the subroutine SOLVE. This subroutine, therefore, ought to be given its own IMPLICIT NONE statement and all variables used (A, B, N, and TEMP_B) specified.
The program is compiled and run with the following statements
% f90 program.f90 % a.out 60.0000000 1.1000000E+02 1.2000000E+02 %In the last call above, where the variable B is not given explicitly, the default argument is used. This means that the default value 20 is added to the actual argument N = 100, which results in A = 120.
It is convenient to place the interface INTERFACE in a module so the user does not have to worry so much about it. The interface is a natural complement to the routine library. Fortran 90 looks automatically for modules in the present directory, in the directories given in the I-list and also in /usr/local/lib/f90: the standard library for Fortran 90 using UNIX. The concept I-list can be used to introduce a directory where various modules may be located, as explained in some of the system oriented sub-pages of Appendix 6. If you forget INTERFACE or have an incorrect interface, usually compilation or execution gives the error message "Segmentation error", and nothing more.
Note that if an output variable is given as OPTIONAL and INTENT(OUT), then you have to have it included in the argument list, if when the program is executed, it assigns a value to this variable. You can not therefore use only OPTIONAL in order to choose whether you wish to have a certain variable outputted or not. The solution to this problem is to use the PRESENT statement also.
(8.1) Write a routine for the calculation of an integral of a function. You will use keyword arguments and default arguments so that
(8.2) Write the interface that is required in the calling routine
in order to use the above integration routine.
Solution.