Please, I would like to request your help with the following problem: I have to define a large array containing zeros which don’t fit in a single row due to I’m exceeding the maximun numbers of character per row. For example:
However, the second row cannot start with a zero given that, when compiling, I get this error
" Syntax error in array constructor at (1). Zero is not a valid statement label at (1)"
Updated: in fact, no. See the post by @themos downward: Problem with array definition - #9 by themos
In free-form format, there is no error and no need to add an &. And in fixed-form, the trailing & is not accepted.
By the large number of 0-elements in the examples above, on one hand, and some prior exposure to Python’s scripy library on the other I noticed Fortran seems equally to work with sparse matrices (or, perhaps more suitable for the parlance of Fortran, a sparse arrays). One of the entries found is this one.
Re: the “data statement,” note the use of DATA also imparts the SAVE attribute to the variable, essentially making it a static variable and adversely impacting thread-safety. Coders may not want that attribute in modern applications.
An option to consider if implied-do is of interest is
a = [( xx, integer :: i = 1, n )] !<-- xx can be a constant such as zero, or a valid expression involving `i`
Hello,
I am guessing you are using the gfortran compiler and you wrote something like this and saved it in a file foo.f.
c234567
dimension a(6)
a=[0,0,0, &
0 ,0,0]
end
What went wrong here is that you used free-format Fortran but the conventions of gfortran treat the contents of foo.f as fixed-form Fortran. In fixed-form the trailing ampersand (&) is an error (which is the Error: Syntax error in array constructor at (1)) and that first zero on line 3 is interpreted as a statement label and not part of a statement (which is the Zero is not a valid statement label at (1))
If you write free-format Fortran you must either put it in a file with a filename extension that the compiler expects (most compilers will accept .f90 for this) or override the compiler’s defaults with a command line option (in gfortran’s case, -ffree-form)
It is also possible to initialize the array with a constant:
module mymod
implicit none
integer, parameter :: n = 20
real :: a(n) = 0 ! implicit save
end module
program main
use mymod
print *, a
end program
Edit: for any new Fortran programmers, the following might be more illustrating of what implicit save means
module mymod
implicit none
real :: a(5) = 0 ! implicit save
end module
module usemymod
use mymod, only: a
implicit none
private
public :: modify_a
contains
subroutine modify_a()
a(1) = 42.
end subroutine
end module
program main
use usemymod, only: modify_a
call modify_a
block
use mymod, only: a
print *, a ! a(1) equals 42.
end block
end program