Creating temporary array when declared in a module

117 Views Asked by At

I do not understand why gfortran creates a temporary array only in one case. Consider the following program

program temporary_arrays
  use Mvars, only       : am
  use Mtemporaries, only: create_matrix
  implicit none
  integer, parameter    :: dp = kind(1.d0), n = 3
  real(dp), allocatable :: bm(:, :)
  
  allocate(am(n, n), bm(n, n))

  ! -- temporary array is created --
  am = create_matrix(n)

  ! -- no temporary array --
  bm = create_matrix(n)
  
end program temporary_arrays

!------------------------
module Mtemporaries

contains
  function create_matrix(n) result(A)
    implicit none
    integer, parameter :: dp = kind(1.d0)
    integer  :: n
    real(dp) :: a(n, n)
    A = 0.d0
  end function create_matrix

end module Mtemporaries  

!------------------------
module Mvars
  implicit none
  integer, parameter       :: dp = kind(1.d0)
  real(dp), allocatable    :: am(:, :)
  
end module Mvars

When compiled with gfortran (GNU Fortran (Homebrew GCC 13.2.0) 13.2.0 Copyright (C) 2023 Free Software Foundation, Inc.) with the -Warray-temporaries option, I get that temporary array is created only in one case, namely when the array is declared in a different module. No such warning when the array is declared in the main program.

I would like to know the logic behind and how to deal with this problem, i.e., avoid creation of temporary arrays.

0

There are 0 best solutions below