Reputation: 4018
I am trying to initialize an array using DATA
statement in Fortran 90. The code is following:
PROGRAM dt_state
IMPLICIT NONE
INTEGER :: a(4), b(2:2), c(10)
DATA a/4*0/
WRITE (6,*) a(:)
DATA a/4,3,2,1/
WRITE (6,*) a(:)
END PROGRAM dt_state
I expected that results on the screen will be 0 0 0 0
and 4 3 2 1
. However, what I got is 0 0 0 0
and 0 0 0 0
. It means DATA
statement does not overwrite the values of a
, does it?
Upvotes: 2
Views: 924
Reputation: 32366
Your code is not standard-compliant. That is: from F2008 5.2.3:
A variable, or part of a variable, shall not be explicitly initialized more than once in a program.
The DATA
statement (is one thing that) performs such explicit initialization (5.4.7.1), and so in particular two cannot appear for the same variable.
For your second "initialization", use assignment. [As given by @VladimirF who is a faster typist than I.] Further, while one can put a DATA
statement with executable statements, as in this case, the standard goes as far as making that obsolescent (B.2.5):
The ability to position DATA statements amongst executable statements is very rarely used, unnecessary, and a potential source of error.
As the code is non-standard, and the error is not one the compiler is required to detect, the compiler is free to whatever it likes with the code. I thought it would be interesting to see what we do see with a small selection:
Of course, one wouldn't want to rely on any of these behaviours, even if it was a desired one.
Upvotes: 2
Reputation: 59998
A variable can appear in a DATA statement only once. The DATA statement is for initialization, which is done only once at program start.
In executable code use assignment to set array values
a = (/ 4, 3, 2, 1 /)
(in Fortran 90)
or
a = [ 4, 3, 2, 1 ]
(in Fortran 2003).
It is better to use this syntax also for initialization.
Upvotes: 6