Fortran 2018 RESULT statement followed by RETURN in internal functions: portable or unspecified?
0 reputation · 17 Aug 2024, 17:28 UTC
0 reputation · 17 Aug 2024, 17:28 UTC
I am reviewing a codebase that targets the Fortran 2018 standard and contains internal functions where a RESULT assignment is immediately followed by a RETURN statement. The standard defines how RESULT assigns the function value, but I cannot find wording that explicitly permits or forbids placing RETURN directly after it, which appears to leave the construct in unspecified territory.
My understanding is that mainstream compilers (gfortran, Intel Fortran, and similar) typically accept this pattern, but vendor documentation is inconsistent about whether the trailing RETURN is a no-op or undefined behavior. This matters because the code must compile and behave identically across several compiler versions and standard-compliance modes, and I want to avoid relying on an extension that could change in a future release.
RETURN immediately after RESULT unspecified, or is there normative wording I have missed that settles it?35275 reputation · 17 Aug 2024, 23:31 UTC
Yes. A RETURN statement immediately after assigning to the RESULT variable in an internal function is portable and standard-compliant in Fortran 2018. The standard does not leave this unspecified.
The value of a function is determined by the value of the variable named in the RESULT clause at the point of termination of the procedure. A RETURN statement explicitly terminates execution of a procedure and returns control to the caller. The RETURN statement does not clear or reset the RESULT variable; it returns using the current state of that variable.
Therefore assigning to RESULT and then executing RETURN is a normal explicit exit path. An implicit return by reaching the end of the function body is functionally equivalent.
Mainstream compilers treat the sequence as standard. There is no normative conflict between RESULT assignment and RETURN because they perform distinct operations: RESULT assignment updates the designated return storage, RETURN transfers control.
No documented portability risk requiring refactoring has been reported for non-recursive internal functions. Warnings about unreachable code or unused result would appear if the compiler considered the construct invalid.
-std=f2018 for gfortran or /std:f18 for Intel Fortran.-Wall -Wextra, and check for unreachable code or unused result alerts.One diagnostic detail that changes the recommendation is whether the internal functions are declared RECURSIVE. If so, confirm the RESULT clause is present and the function does not alias its own name, as RESULT handling is mandatory for recursive functions.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.