1

In C I can easily return a value from a function:

int foo(int b) {
   if (b == 0) return 42;
   int a;
   // calculate a
   return a;
}

But in Fortran the RETURN statement serves error handling. I could do

integer function foo(b)
    integer :: b, a
    if (b == 0) ! what should I enter here??
    // calculate a
    foo = a
end function

How do I do this in modern Fortran?

I know that in this case and if-then-else-endif would suffice. But there are cases when it wouldn't and I don't want to make an overly complex example.

marmistrz
  • 5,974
  • 10
  • 42
  • 94

2 Answers2

3

In Fortran you use the return statement to exit a procedure.

Graham
  • 7,431
  • 18
  • 59
  • 84
1

As noted in the earlier answer, the return statement completes execution of a procedure (strictly, a subprogram). To explicitly give an example suited to the question

integer function foo(b)
    integer :: b, a
    if (b == 0) return
    !! calculate a
    foo = a
end function

completes the function immediately if that condition is met.

However, in this case this doesn't actually give us legal Fortran code, and certainly not want we want, and we need to do a little more.

Whenever a function completes, the function result, if not a pointer, must have its value defined. That value takes the place of the function reference in the calling scope. [If it is a pointer, then the requirement is that the function result must not have its pointer association status undefined.]

Now, the function result is called foo in this case. As long as we assign to foo before we return the function will return the given value. For example:

integer function foo(b)
    integer :: b, a
    foo = 42
    if (b == 0) return
    !! calculate a
    foo = a
end function

or

integer function foo(b)
    integer :: b, a
    if (b == 0) then
      foo = 42
      return
    end if
    !! calculate a
    foo = a
end function

Note that, rather than calculating a and then just before the end function assigning to foo, we can just assign directly to foo. If you understand that then the "premature return of a value" becomes quite intuitive.

francescalus
  • 30,576
  • 16
  • 61
  • 96