How to use inteface blocks to pass a function to a subroutine?

前端 未结 3 656
旧巷少年郎
旧巷少年郎 2021-01-24 06:24

I understand the interface command can be used to pass a a function into a subroutine. So for example in the main program I\'d define some function and then pass it to some subr

3条回答
  •  既然无缘
    2021-01-24 07:20

    Module:

    module fmod
        interface
           function f_interf(x,y)
           real, intent(in) :: x, y
           real :: f_interf
           end function
        end interface
    
    contains 
        function f_sum(x,y)
        real, intent(in) :: x, y
        real f_sum
    
        f_sum = x + y
    
        end function
    
        function f_subst(x,y)
        real, intent(in) :: x, y
        real f_subst
    
        f_subst = x - y
    
        end function
    
        subroutine subr(limit1, limit2, func, ans)
        real limit1, limit2
        procedure(f_interf) func
        real ans
    
        ans = func(limit1, limit2)
        end subroutine
    end module
    

    main program:

    program pass_func
    use fmod
    Implicit None
    real ans, limit1, limit2
    limit1 = 1.0
    limit2 = 2.0
    call subr( limit1, limit2, f_subst, ans)
    write(*,*) ans
    call subr( limit1, limit2, f_sum, ans)
    write(*,*) ans
    end program pass_func
    

    and output:

      -1.000000
       3.000000
    

提交回复
热议问题