Fortran 显式接口中自动对象的维度检查
我一直认为,当例程在给出显式接口的模块中定义时,在子例程定义中以自动大小的伪参数给出值在错误检测中有一定的好处。但以下示例表明,实际上并没有检查数组边界:Fortran 显式接口中自动对象的维度检查,fortran,fortran90,subroutine,Fortran,Fortran90,Subroutine,我一直认为,当例程在给出显式接口的模块中定义时,在子例程定义中以自动大小的伪参数给出值在错误检测中有一定的好处。但以下示例表明,实际上并没有检查数组边界: module test_mod Implicit none contains !> Testing routine that has an automatic array arr of length n. The integer n is also given. !> It is included i
module test_mod
Implicit none
contains
!> Testing routine that has an automatic array arr of length n. The integer n is also given.
!> It is included in a module and has an explicit interface.
subroutine print_array(n, arr)
Integer, intent(in) :: n !< Size of arr
Integer, Dimension(n), intent(in) :: arr !< A test array that should be of size n
Integer :: i
do i = 1, n
print *, 'number:', i, arr(i)
enddo
End Subroutine print_array
end module test_mod
program playground
use test_mod, only : print_array
! Call print_array with an array smaller than 3 elements
Call print_array(3, [8, 9])
end program playground
因此,第三个值在arr
边界之外,在我的例子中,将打印-858993460。据我所知,在编译时通常无法捕捉到这种行为。但即使将ifort
与/check:bounds
选项一起使用,也不会在运行时发出错误消息
因此,我想问,使用
维度(n)
来指定arr
是否是一种好的做法,或者使用维度(:)
来定义它是否更好。以这种方式提供维度有什么好处?可能会对您有所帮助。一般来说,我不认为将数组及其大小作为单独的参数传递有什么意义,自从20多年前Fortran 90被广泛应用以来就没有了。在极少数情况下,我会编写依赖于知道数组大小的代码,我会在例程中计算出来。我不知道这是否被广泛认为是一种好的做法,但它对我来说是有效的。在例程参数声明中,dimension(n)
不再有什么用处了。
number: 1 8
number: 2 9
number: 3 -858993460