Suppose I have a file that each line contains an array index followed by the array value
i array(i)
Can I read in the data by just a naive read(unit=10, *) i, array(i)
? Will Fortran always read i
first and then use this i
value to assign array(i)
? Will certain read
specifications or compiler flags influence the behavior?
The data transfer statement
read(unit=10,*) i, array(i)
is a legitimate one, and its behaviour is as desired: from the record the value for i
is first read, then that value is used to identify the element of the array array(i)
for the second value read.
This is a requirement of the Fortran specification, such as with (Fortran 2018, 12.6.4.5.1):
All values needed to determine which entities are specified by an input/output list item are determined at the beginning of the processing of that item.
Of course, although this data transfer statement potentially works, that doesn't mean that it is desirable in all but the simplest cases where you trust the input data. In particular, it is not possible to do any checking of the bounds during this read statement. If the i
value read corresponds to an invalid array element specification, the program is broken. You may want to use an intermediate value for the array element merely to handle potential problems with the input file.