Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are the MAX and MIN functions implemented in Fortran without support for variadic functions?

Unless I'm mistaken, there is no way in Fortran to write a function or subroutine with an arbitrary number of arguments (known more succinctly as a variadic function).

For example: RESULT = FUNC(A1, A2 [, A3 [, ...]])

I know, I can create optional arguments, but the number of arguments is finite and must be manually declared, one by one, in the function definition.

So how then is the Fortran compiler implementing, MAX or MIN which are, in fact,

RESULT = MAX(A1, A2 [, A3 [, ...]])

What is especially baffling, is that these variadic MAX and MIN functions are, evidently, part of the Fortran 77 standard. So whatever capability exists to implement these functions must have been available around 1977.

like image 687
EMiller Avatar asked Jun 16 '16 20:06

EMiller


1 Answers

A variadic function is support by the compiler that allows a programmer to write a function which accepts a variable number of arguments.

Even if it might look the same to a programmer, MAX() in Fortran is not required to be a function, variadic or otherwise - it can be implemented as a capability built into the compiler to recognise a sequence of tokens and expressions, and emit as much code (e.g. to an object file) as needed to produce the required result. That might involve calling library functions, or it might not.

For example, given

  RESULT = MAX(A,B,C)

all that is needed is recognition of the arguments, A, B, and C during syntactic analysis and (subject to the statement/expression being valid - such as all three having the same type and kind) emit code that steps over each argument to find the maximum.

So the compiler might translate something like

  RESULT = MAX(A,B,C)

into something which looks (assuming we have a Fortran compiler that emits C code) like

  result = a;
  if (b > result) result = b;
  if (c > result) result = c;

and simply emit an additional bit of logic to the above to handle each additional parameter.

And, yes, such capability existed in compilers well before 1977. Such capability is one of the primary points of having a compiler - automate the process of converting something simple for the programmer into whatever more complicated logic is needed.

like image 131
Peter Avatar answered Oct 19 '22 19:10

Peter