The data statement is another way to input data that are known at the time when the program is written. It is similar to the assignment statement. The syntax is:
data list-of-variables/ list-of-values/, ...
Where the three dots means that this pattern can be repeated. Here is an example:
data m/10/, n/20/, x/2.5/, y/2.5/
We could also have written this:
data m,n/10,20/, x,y/2*2.5/
We could have accomplished the same thing by the assignments:
m = 10 n = 20 x = 2.5 y = 2.5
The data statement is more compact and therefore often more convenient. Notice especially the shorthand notation for assigning identical values repeatedly.
The data statement is performed only once, right before the execution of the program starts. For this reason, the data statement is mainly used in the main program and not in subroutines.
The data statement can also be used to initialize arrays (vectors, matrices). This example shows how to make sure a matrix is all zeros when the program starts:
real A(10,20) data A/ 200 * 0.0/
Some compilers will automatically initialize arrays like this -- but not all, so if you rely on array elements to be zero it is a good idea to follow this example. Of course you can initialize arrays to other values than zero. You may even initialize individual elements:
data A(1,1)/ 12.5/, A(2,1)/ -33.3/, A(2,2)/ 1.0/
Or you can list all the elements for small arrays like this:
integer v(5) real B(2,2) data v/10,20,30,40,50/, B/1.0,-3.7,4.3,0.0/
The values for two-dimensional arrays will be assigned in column-first order as usual.
The data statement cannot be used for variables contained in a common block. There is a special "subroutine" for this purpose, called block data. It is not really a subroutine, but it looks a bit similar because it is given as a separate program unit. Here is an example:
block data integer nmax parameter (nmax=20) real v(nmax), alpha, beta common /vector/v,alpha,beta data v/20*100.0/, alpha/3.14/, beta/2.71/ end
Just as the data statement, block data is executed once before the execution of the main program starts. The position of the block data "subroutine" in the source code is irrelevant (as long as it is not nested inside the main program or a subprogram).
Copyright © 1995-7 by Stanford University. All rights reserved.
[ Index ]