Fortran: passing same array as two dummy arguments to subroutine
Asked Answered
G

2

6

Suppose I have a subroutine which accepts two arrays as input. One is given intent(in) and the other is given intent(out). The latter is derived from the former in an arbitrary manner. However, what if I pass through the same actual argument for both dummy arguments? In general, the result will not be what was intended by the subroutine. See code snippet below.

The problem is, the compiler doesn't seem to care, even though I've given intent flags. I'm using Intel Visual Fortran Composer 12, with all diagnostics. Is there a better way of coding the subroutine, or some compiler option I'm missing, to make the code safer?

module foo

    contains

    subroutine sub_a()
        implicit none
        real::array(10,10)

        call sub_b(array,array)

    end subroutine

    subroutine sub_b(array1,array2)
        implicit none
        real,intent(in)::array1(10,10)
        real,intent(out)::array2(10,10)

        !array2 is derived from array1 somehow

    end subroutine

end module foo
Golanka answered 22/8, 2011 at 1:0 Comment(0)
B
8

This is called aliasing -- referring to the same item by two different names. In most cases this is not allowed in Fortran. Your example is not legal Fortran -- see http://software.intel.com/en-us/blogs/2009/07/10/doctor-fortran-in-ive-come-here-for-an-argument-side-2/, which has this specific case, of aliasing via the same actual argument used for two dummy arguments. Fortran compilers are not required to diagnose all violations of the rules of the language and this appears to be an example that the compiler is not recognizing.

Edit: aliasing is permitted. What is forbidden is changing the value of the dummy argument through the alias, here the other dummy argument. The rules are less restrictive for pointer and target arguments. The specific rules are described in "The Fortran 2003 Handbook" by Adams et al.

Batrachian answered 22/8, 2011 at 2:0 Comment(2)
Thanks, that clears it up. It's unfortunate Intel Visual Fortran gives no warning for this. I guess the only solution is discipline in using appropriate subroutine calls.Golanka
What do you think about comparing the location of the two inputted arrays? Is that a safe thing to do? Also, apparently F2003 does not implement the loc function, is there an equivalent?Golanka
R
1

Putting parentheses around the argument that is intent(in) makes the code legal since you are effectively passing a copy:

call sub_b((array),array)
Razzledazzle answered 31/3, 2014 at 19:44 Comment(1)
is this part of Fortran standard?Veer

© 2022 - 2024 — McMap. All rights reserved.