Quantcast
Channel: Intel® Fortran Compiler
Viewing all articles
Browse latest Browse all 3270

Functions returning arrays, derived types and the creation of temporaries.

$
0
0

Dear all,

Consider the following situation followed up by a working test case.

Let there be a derived type wrapping a multidimensional array. Let there further be a function "sum" which adds array components of the objects of a derived type and returns the resulting array. Furthermore, there is a "from_array" assignment subroutine which takes an object and an array, then fills the array component of the object with its array argument.

I am interested how does the compiler interpret an expression such as c = sum(a,b), where = corresponds to "from_array". Is this going to be  optimised into c%arr=a%arr + b%arr, or is an (unnecessary) temporary going to be produced first, e.g: temp=a%arr+b%arr;c%arr=temp?

In the following example, the derived type is "board" (line 3), its objects a,b,c and the statement in question: c=sum(a,b) (line 53). Function "from_array" is also defined as an assignment (lines 7 and 27), and "sum" is defined on line 14.

 

module board_module
  implicit none
  type board
     real,dimension(:,:), allocatable :: arr
  end type board

  interface assignment(=)
     ! Call from_arr "="
     module procedure from_arr
  end interface assignment(=)


contains
  function sum(x,y)
    ! Add x%arr and y%arr, then return the resulting _array_
    type(board), intent(in) :: x,y
    real,dimension(size(x%arr,1),size(x%arr,2)) :: sum !Is there a
                                                       !more concise
                                                       !way of
                                                       !specifying an
                                                       !automatic
                                                       !multidimensional
                                                       !array object?
    sum = x%arr+y%arr
  end function sum

  subroutine from_arr(dest,src)
    ! Take the src array, and fill dest%arr with it.
    type(board),intent(inout) :: dest
    real,dimension(:,:),intent(in) :: src
    dest%arr = src
  end subroutine from_arr

  subroutine make_board(dest,d1,d2)
    ! Allocate arr
    type(board),intent(out) :: dest
    integer,intent(in) :: d1,d2
    allocate(dest%arr(d1,d2))
  end subroutine make_board
end module board_module

program add
  use board_module
  implicit none
  type(board) :: a,b,c

  call make_board(a,10,20)      !Allocations
  call make_board(b,10,20)
  call make_board(c,10,20)
  a%arr=2                       !Assign some stuff
  b%arr=3

  c = sum(a,b)                  !Is this "temp=a%arr+b%arr;c%arr=temp", or "c%arr=a%arr+b%arr" for the compiler?

  print *, c%arr
end program add

 


Viewing all articles
Browse latest Browse all 3270

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>