In the following code, the upper bounds of the DO loops are modified within the loop as
integer :: i1, i2, n1, n2
n1 = 4 ; n2 = 1
do i1 = 1, n1
do i2 = 1, n2
print *, "i1 =", i1, "i2 =", i2
n1 = 2
n2 = 2
enddo
enddo
for which gfortran4.8 and ifort14.0 give the following result:
i1 = 1 i2 = 1
i1 = 2 i2 = 1
i1 = 2 i2 = 2
i1 = 3 i2 = 1
i1 = 3 i2 = 2
i1 = 4 i2 = 1
i1 = 4 i2 = 2
This indicates that the bounds are fixed upon entry of each DO loop (i.e., the upper bound of i1 is fixed to 4 despite that n1 is modified to 2 inside the loop). This behavior is in contrast to that of C/C++, where the corresponding code
int n1 = 4, n2 = 1;
for( int i1 = 1; i1 <= n1; i1++ )
for( int i2 = 1; i2 <= n2; i2++ )
{
printf( "i1 = %d i2 = %d\n", i1, i2 );
n1 = 2;
n2 = 2;
}
gives
i1 = 1 i2 = 1
i1 = 1 i2 = 2
i1 = 2 i2 = 1
i1 = 2 i2 = 2
which is reasonable because of the definition of for loops (i.e., begin, end, and increment conditions). So my question is: Is it okay to assume that the above behavior of DO loops is general (= defined by the Fortran standard) or compiler-dependent (i.e. a different compiler from ifort or gfortran might behave differently)?
The Fortran standards specify that the number of iterations of a DO
loop is fixed on commencement of the loop, using the formula (at least until F95, when ability was removed to use non-integer loop control expressions)
iterations = MAX(0,INT((final-value - initial-value + step-size)/step-size)
One consequence of this is the behaviour you are seeing: changing any of the values used to control the loop within the loop body does not change the number of iterations that will be executed.