- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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
Link Copied
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Your function could be written as
[fortran]
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
[/fortran]
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(*,*)
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Hello Mark,
Thank you.

- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page