1

I am just getting started with Fortran and I want to write a simple function which takes three real numbers as arguments and returns a vector containing 3 real numbers, but I have difficulties with the Fortran syntax:

function foo(x,y,z) result(res)
    real, intent(in) :: x,y,z
    real, intent(out) :: res(3)
    res=[x**x,y**y,z**z]
end function foo

program function_test
    implicit none
    real :: res(3)                      !declare the array res
    real :: foo(3)                      !declare the return type of the function foo
    res=foo(1.0,1.0,1.0)                !call foo and save the resulting vector in res
    print *,"1st component:",res(1)     !Print the first element of the result array
    print *,"2nd component:",res(2)     !Print the second element of the result array
    print *,"3rd component:",res(3)     !Print the third element of the result array
end program function_test

Compiling the above code with gfortran results in an error message Error: Rank mismatch in array reference at (1) (3/1). Now I understand that the statement res=foo(1.0,1.0,1.0) seems to be interpreted as "take the element [1,1,1] of the three dimensional array foo" which is of course incorrect, but how can I call foo and store the resulting array in res?

(As far as I understand, the line real :: foo(3) in function_test is necessary to define the return type of foo).

francescalus
  • 30,576
  • 16
  • 61
  • 96
Mantabit
  • 269
  • 1
  • 4
  • 14
  • You essentially have two problems, both of which I address in [this answer](https://stackoverflow.com/a/24170990/3157076) to another question. Firstly, you cannot use `intent(out)` for the function result; secondly, you must have an _explicit interface_. In your main program `real :: foo(3)` declares a local array variable, not a function returning an array, so you'll also have problems with real-value indexes for the array which, although is rank-1, you attempting to reference with three indexes. This latter is the source of the compiler message but isn't really your problem. – francescalus Jan 02 '19 at 17:38

0 Answers0