Constant and pass-by-reference

Tobias Burnus burnus@net-b.de
Tue Jun 18 21:32:00 GMT 2019


Hi Hafiz,

to add to what Arjen wrote.

Am 18.06.19 um 15:13 schrieb Hafiz Abid Qadeer:
> a general issue with a 'parameter' being passed by reference. The following program demonstrate the problem. The example looks contrived but actual code used the "var" in an openacc kernel and it gets written due to an implicit copy clause. […]
>
> As I understand it, a constant value is passed to a subroutine which
> tries to modify it. As value was passed by reference, the callee tries
> to write to read-only memory and segfaults.

Fortran by default passes values by reference.* If you use the VALUE
attribute, i.e.,

      subroutine  crash(var)
        implicit none
        integer var
        value var
or
        integer, value :: var
the variable is passed by value.*

(*The Fortran standard actually does not state how it is passed, it just
states the semantic. Depending on the argument type, passing as VALUE
might not work or semantic might require, e.g., contiguous memory. Then
the caller generates a temporary value with (depending on the "intent")
copy-in and/or copy-out and passes this one as a pointer.)


> Also I am wondering should compiler issue a
> warning in such cases as I did not see a warning even with -Wall.

Warning is not that simple without specifying an "intent(in)",
"intent(out)" or "intent(inout)". With intent, the compiler can check
this at compile time, otherwise it would need to keep track whether the
variable is always modified, assume:

if (var !=5) then

  var = 4

end if

In this case, the program would work and be perfectly valid as the
parameter g_var is not modified.

Tobias

PS: I head that in the old days, such a program didn't crash but did
modify the value of the constant. That would even work for:
"call crash(5)" - after which "5" had the value 4. But that ways decades
before my first encounter with Fortran.



More information about the Fortran mailing list