Different syntaxes to declare arrays: with and without the dimension statement [duplicate]

亡梦爱人 提交于 2020-01-04 10:05:11

问题


I'm using gfortran version 7.2.0. I'm quite new to Fortran. I know there are different versions of Fortran. In the code below, I'm declaring arrays (or actually tensors) using different syntaxes

program arrays
    implicit none

    integer :: m(3, 4)
    integer, dimension(3, 4) :: n

    print *, "m = ", m
    print *, "n = ", n

end program arrays

In one case, I'm using the dimension statement, in the other I am not. This program compiles (without errors). I'm using the gfortran's flags -g and -fbounds-check. The file extension of the file with the program above is f.90.

Why are there different syntaxes to apparently declare arrays in Fortran? Which versions of Fortran support which syntaxes, or is the possibility to declare the rank, shapes and extents of arrays as for m just an extension of the compiler?


回答1:


The statements

integer :: m(3, 4)
integer, dimension(3, 4) :: n

are both standard Fortran since Fortran 90. Without the use of the :: the first line like

integer m(3,4)

would be valid before Fortran 90.

Before coming to something else, the ,dimension isn't a dimension statement but an attribute specification. A dimension statement would be

dimension n(3,4)  ! With n implicitly or explicitly typed elsewhere

The important thing here is that attributes specified with type declaration apply to (almost) all objects declared. So

integer :: m1(3,4), m2, m3
integer, dimension(3,4) :: n1, n2, n3

sees m1 a rank-2 array, but m2 and m3 scalars (unless given array properties elsewhere or are actually functions) whereas n1, n2 and n3 are all rank-2 arrays of shape [3,4]

The two declarations of the question could then be simply

integer, dimension(3,4) :: m, n

The "almost" comes from the fact that we can have

integer, dimension(3,4) :: n, p(5)

where the shape of p is [5], overriding the [3,4] specified earlier.



来源:https://stackoverflow.com/questions/46142036/different-syntaxes-to-declare-arrays-with-and-without-the-dimension-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!