Upper bounds of Fortran Do loops

In the following code, the upper bounds of the DO stacks change inside 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 boundaries are fixed when each DO cycle is entered (i.e., the upper boundary i1 is fixed to 4, despite the fact that n1 is changed to 2 inside the cycle). This behavior is different from 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 for loops (i.e., start, end, and increment conditions). Therefore, my question is: can we assume that the behavior of DO loops described above is general (= defined by the Fortran standard) or depends on the compiler (i.e., the other compiler from ifort or gfortran may behave differently)?

+4
source share
1 answer

Fortran standards determine that the number of iterations of the DO loop is fixed at the start of the loop using the formula (at least until F95, when the ability was removed to use non-target loop control expressions, as noted by francescalus in the comments)

 iterations = MAX(0,INT((final-value - initial-value + step-size)/step-size) 

One consequence of this is the behavior you see: changing any of the values ​​used to control the loop inside the loop body does not change the number of iterations that will be performed.

+4
source

All Articles