Question

I am using fortran for a while, but I didn't check the implicit cast issue when using subroutines in fortran. For example

    subroutine printa(a)
        double precision :: a
        ...
    endsubroutine printa

When I called the subroutine

    call printa(1)

I saw error #6633: The type of the actual argument differs from the type of the dummy argument. [1] I know it is because I use an integer instead of a double precision as an input parameter. But I just realized that there is no implicit cast when using subroutines.

If I want a subroutine which handles integer and double precision data, it seems I have to define 2 subroutines for doing these things. Is there a way to make the implicit cast happen (just like the function calling in c)? Or there is another way to make it?

Thanks.

Was it helpful?

Solution

It is fundamental in Fortran that reals (including different precisions) and integers are different and that you need different subroutines to handle them. If you want the convenience of having a single call, similar to Fortran intrinsics such as sin which are implicitly several different functions, you can write the several different procedures and then create a generic interface to select between them. Fortran will then select the correct actual procedure based on the actual arguments, to match the dummy arguments. Here is an example that does it by rank of the array argument: how to write wrapper for 'allocate'. It can also be done, as you wish, by type of the argument.

OTHER TIPS

You can overload a subroutine name so that when the "wrong" type of argument is supplied it is converted to right type and used to call the subroutine, as shown below.

module foo
implicit none
interface printa
   module procedure print_int,print_real
end interface printa
contains
!
subroutine print_real(x)
real, intent(in) :: x
print*,"number is ",x
end subroutine print_real
!
subroutine print_int(i)
integer, intent(in) :: i
call print_real(real(i))
end subroutine print_int
!
end module foo

program main
use foo, only: printa
implicit none
call printa(1)
call printa(1.0)
end program main

Output:

number is 1.

number is 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top