Search code examples
arraysfortransubroutine

Can I pass arrays with undefined dimension to a Fortran subroutine as INTENT(INOUT)?


I need to pass arrays of variables to a subroutine that should change their values according to an external file. The problem is that this should be as generic as possible so if the file has n values I should be able to pass n generic integers.

Here is an example of my code:

program dummy
    
    use checkpt
    implicit none

    integer :: i1=0, i2=0, k=1, n, cpt
    integer*8 :: lastTime

    call load_checkpoint(ints=[k,i1,i2])
    
    --some code happening--

end program dummy

And the subroutine called is the following:

subroutine load_checkpoint(ints)
        implicit none

        integer, intent(inout) :: ints(:)
        integer :: stat

        open(8989, file='temp.txt', status='old', action='READ', iostat=stat)
        if (stat .eq. 0) then
            read (8989,*,iostat=stat) ints
        end if
        close(8989)

    end subroutine load_checkpoint

What I get is Error: Non-variable expression in variable definition context (actual argument to INTENT = OUT/INOUT) at (1) and I can't understand why. I also tried with non initialized variables but I get the same error. Can anybody help me, please?


Solution

  • If a dummy argument is intent(out) or intent(inout), then the actual argument shall not be an expression. Your actual argument [k,i1,i2] is an expression (more precisely an array constuctor, that builds here a rank one array from 3 scalar variables), this is why you get an error here.

    If you want your variables k, i1 and i2 to be updated at the end you have to write more lines (and in the called subroutine you should attribute only intent(out) to ints, as you don't use at all the input values):

    integer :: ints(3)
    call load_checkpoint(ints=ints)
    k  = ints(1)
    i1 = ints(2)
    i2 = ints(3)