How to return a value from a fortran function

How to return a value from a fortran function

I would like to return a value from a function to the main program. I would also like to be able to use that value at the main function. Here is an example that doesn't work.

 

    

      program trial

      real*8 a,b,c

      a=1.d0

      b=0.d0

     

      call fn(a,b,c)

     

      if (fn.eq.1) write(*,*)

  

      end program trial

 

      function fn(a,b,c)

      real*8 a,b,c

     

      if (a.gt.0) return 0

 

      return 1

      end function fn

3 Beiträge / 0 neu
Letzter Beitrag
Nähere Informationen zur Compiler-Optimierung finden Sie in unserem Optimierungshinweis.

Your function could be written as

function fn(a, b, c)
    integer :: fn ! I'm declaring the function return value as integer here because of the integer return values in the original code, implicit typing would make it real otherwise.
    real*8 a, b, c
    if (a .gt. 0) then
        fn = 0 ! This assignment sets the return value of the function...
        return
    end if
    fn = 1 ! ... and so does this
end function

You will need to declare the function as integer fn in your program.

To call it, either

a) Declare an integer in your program to receive the return value, say retval and call the function with retval = fn(a,b,c); if (retval .eq. 1) write(*,*)

b) Call the function in the if statement: if (fn(a,b,c) .eq. 1) write(*,*)

Hello Mark,

 

Thank you.

Melden Sie sich an, um einen Kommentar zu hinterlassen.