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

1

5

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.

Iota answered 16/6, 2016 at 20:52 Comment(2)
Yes, you and I can't write a true variadic function, but I also read this question as "why don't Fortran intrinsics alway follow the rules of user-defined procedures?". Essentially: why should they? That is, the Fortran compiler isn't constrained to implement min in the way that we would. It can do whatever it likes (probably as a C program itself) as long as it gets the answer required of it.Orna
Yes, your alternate reading of the question is something that also crossed my mind and I came to the same conclusion as you, "Essentially: why should they?". But I still find it frustrating nonetheless.Iota
P
7

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.

Pancratium answered 16/6, 2016 at 21:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.