Comp Sci Return vector from function (fortran 95)

  • Thread starter Thread starter fortrannewbe
  • Start date Start date
  • Tags Tags
    Function Vector
AI Thread Summary
Returning an array from a function in Fortran 95 can be problematic when the function is defined within a module. The user finds that the function works correctly when placed inside the main program block but encounters issues when defined in a module. They suggest that while a function can be declared as a certain type, declaring it as an array may lead to inconsistencies across different compilers. Testing with another compiler revealed that both implementations of the function worked, indicating potential compiler-specific behavior. The discussion highlights the importance of compiler compatibility when working with Fortran modules and functions.
fortrannewbe
Messages
3
Reaction score
0
Hi,
i have some problems to return a array or vector from a function that is located in a fortran-module. If i put the function inside the main program block with a "contains" it works, but why does the following not work? Does anyone have an idea?

Thanks
Code:
module testmodule

contains

function testfunction(a)

    real, dimension(3) :: testfunction
    real :: a

    testfunction(1) = a + 10
    testfunction(2) = a + 20
    testfunction(3) = a + 30

end function testfunction

end module testmodule


program testprogram

    use testmodule

    real :: b = 15

    print*, testfunction(b)

end program testprogram
 
Physics news on Phys.org
I believe a function can be declared of a certain type (real, integer, complex, etc.), but I don't think the function name itself can be declared as an array. Arrays, however, can be passed to the function as arguments.

real :: testfunction is OK

real, dimension (3) :: testfunction ??
 
But I think it is possible to declare a function as an array, because it works when I do it in the following order:

Code:
program testprogram

    use testmodule

    real :: b = 15

    print*, testfunction(b)contains

function testfunction(a)

    real, dimension(3) :: testfunction
    real :: a

    testfunction(1) = a + 10
    testfunction(2) = a + 20
    testfunction(3) = a + 30

end function testfunction

end program testprogram
But this is a very horrible way to use the program language, because the program looks disarranged if there are many functions.
 
You may be experiencing some weird, non-standard side effect from the compiler you are using. Your program may not work reliably with another compiler.
 
I tried a different compiler, and now both versions of the code above work. That is very strange.
 

Similar threads

Replies
5
Views
2K
Replies
7
Views
2K
Replies
13
Views
3K
Replies
3
Views
7K
Replies
2
Views
6K
Replies
5
Views
2K
Back
Top