Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we still need subroutines? [closed]

In Fortran, a clear difference exists between function and subroutine: functions return one value, subroutines return no value. This introduce a cascade of differences between the two. One example is the calling semantics: you can call a function just as in other languages, but in order to call a subroutine you must issue a call statement first.

With the addition of pointers and data types in Fortran95, it appears that there is no technical limitation in making any subprogram a function, and keeping subroutines just for legacy. Functions could return zero (you just return a dummy integer), one, or multiple values (for example, you could return a pointer to an allocated instance of a type, like a C++ STL Pair).

Am I wrong? Do we still need subroutines in Fortran programming due to some feature that subroutines have and functions don't?

like image 513
Stefano Borini Avatar asked Oct 15 '10 11:10

Stefano Borini


1 Answers

If you search the comp.lang.fortran archives, you'll find discussions about the semantics of functions. IIRC it turns out that it's not clearly specified in the standard what is and what isn't allowed for functions that have side-effects.

For instance, can the compiler optimize

x = foo(args) + foo(args)

into

x = 2 * foo(args)

Or for another example, consider

x = y + foo(y)

What if foo() changes the value of y? Remember that Fortran doesn't have the C concept of sequence points.

In general, the recommendation by several experts is to use functions only if they're pure, otherwise use subroutines. And, that is advice that I follow myself as well.

like image 75
janneb Avatar answered Sep 20 '22 17:09

janneb