Different syntaxes to declare arrays: with and wit

2019-07-19 02:54发布

问题:

This question already has an answer here:

  • Array declaration in Fortran 2 answers

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.