Fortran 2008: How are function return values ​​returned?

Is it possible in modern Fortran to return an array from a function with a performance equivalent to the fact that the routine will fill the array passed as an argument?

Consider, for example, as a simple example

PROGRAM PRETURN 

  INTEGER :: C(5)
  C = FUNC()
  WRITE(*,*) C
  CALL SUB(C)
  WRITE(*,*) C

CONTAINS 

  FUNCTION FUNC() RESULT(X)
    INTEGER :: X(5)
    X = [1,2,3,4,5]
  END FUNCTION FUNC

  SUBROUTINE SUB(X)
    INTEGER :: X(5)
    X = [1,2,3,4,5]
  END SUBROUTINE SUB

END PROGRAM PRETURN

Here, the string C = FUNC()will copy the values ​​from the return value of the function before dropping the returned array from the stack. The subroutine version CALL SUB(C)will populate directly C, avoiding the extra step of overcoming and using memory associated with a temporary array - but make it impossible to use in expressions such as SUM(FUNC()).

, , , C, . *

, - ?


* , . Intel fortran (re) , , ALLOCATE(C, SOURCE=FUNC()). Gfortran , , ALLOCATE, SOURCE, .

+4
2

Fortran . , . - , , - , . , . , Intel Fortran - .

- . , , .

, Intel Fortran , 17 , .

+7

. , , , , , , fortran.

, , :

function doThings(param) results(thing)
    integer :: thing
    integer, intent(in out) :: param
    ! Local variables
    integer :: genialUpdatedValue, onOfThePreviousResult
    ! some other declarations
    ! serious computation to do things
    ! and compute genialUpdatedValue and onOfThePreviousResult
    param = genialUpdatedValue
    thing = onOfThePreviousResult
end function doThings

:

! some variables first
integer, parameter :: N_THINGS = 50 ! just love 50
integer :: myThing, myParam
integer, dimension(N_THINGS) :: moreThings
!
! Reading initial param from somewhere
! myParam now has a value
!
myThing = doThings(myParam)

,

!
! Reading initial param from somewhere
! myParam now has a value
!
moreThing = doThings(myParam)

?

integer :: i
do i = 1, N_THINGS
    moreThings(i) = doThings(myParam)
end do

integer :: i, thing
thing = doThings(myParam)
do i = 1, N_THINGS
    moreThings(i) = thing
end do

, myParam . , , , , .

, , . , , , , , , . , .

0

All Articles