Fortran Do循环的上限 [英] Upper bounds of Fortran Do loops
问题描述
在下面的代码中,DO循环的上界在循环中被修改为
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
其中gfortran4.8和ifort14.0给出以下结果:
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
这表示边界在每个DO循环进入时是固定的尽管在循环内n1被修改为2,i1的上限固定为4)。这个行为与C / C ++的行为相反,其中相应的代码
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;
}
给予
i1 = 1 i2 = 1
i1 = 1 i2 = 2
i1 = 2 i2 = 1
i1 = 2 i2 = 2
这是合理的,因为定义了for循环(即begin,end和increment条件)。所以我的问题是:是否可以假设DO循环的上述行为是一般的(=由Fortran标准定义)或编译器依赖(即不同的编译器从ifort或gfortran可能表现不同)?
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)?
推荐答案
Fortran标准规定 DO
循环的迭代次数在开始时是固定的使用公式(至少高达F95,当能力被移除以使用非整数循环控制表达式,如francescalus在注释中所指出的)。
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 up to F95, when ability was removed to use non-integer loop control expressions, as noted by francescalus in comments)
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 use to control the loop within the loop body does not change the number of iterations that will be executed.
这篇关于Fortran Do循环的上限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!