Recursion – Fortran finally gets it!

Fortran gave recursion a wide berth until Fortran 90. More than 25 years after ALGOL first allowed recursion, Fortran was finally allowing. Modern Fortran is one of the few languages where the function must be explicitly defined recursive. The prefix recursive must be used before the keyword function.

recursive function fibonacci (n) result (fib_result)
   integer, intent (in) :: n
   integer :: fib_result
   if (n <= 2) then
      fib_result = 1
   else
      fib_result = fibonacci (n-1) + fibonacci (n-2)
   end if
end function fibonacci

In Fortran 2018, the specs changed again. Here procedures without an explicit recursive attribute behave as if recursive is specified. F2018 provides a new attribute non_recursive, which can be used to mark a procedure that may not be called recursively.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.