我很惊讶您不能像这样将数组成员作为 do 循环的控制变量:
program test
integer, dimension(2) :: i
do i(1) = 1, 3
do i(2) = 1, 3
! anything here
write(*, *) i
end do
end do
end program
我的问题是为什么不允许这样做?
编辑:
还是允许但我做错了?
ifort v 11.1 的错误消息是:
test.f90(4): error #5082: Syntax error, found IDENTIFIER 'I' when expecting one of: ( % : . = =>
do i(1) = 1, 3
-------^
test.f90(4): error #5082: Syntax error, found ',' when expecting one of: <END-OF-STATEMENT> ;
do i(1) = 1, 3
---------------^
test.f90(5): error #5082: Syntax error, found IDENTIFIER 'I' when expecting one of: ( % : . = =>
do i(2) = 1, 3
-------^
test.f90(5): error #5082: Syntax error, found ',' when expecting one of: <END-OF-STATEMENT> ;
do i(2) = 1, 3
---------------^
test.f90(4): error #6535: This variable or component must be of a derived or structure type [DO]
do i(1) = 1, 3
----^
test.f90(4): error #6460: This is not a field name that is defined in the encompassing structure. [I]
do i(1) = 1, 3
-------^
test.f90(8): error #6099: An ENDDO statement occurred without a corresponding DO or DO WHILE statement.
end do
----^
test.f90(9): error #6099: An ENDDO statement occurred without a corresponding DO or DO WHILE statement.
end do
----^
来自 gfortran V4.5.1 & 4.8.3 的错误信息是:
test.f90:4.4:
do i(1) = 1, 3
1
Error: Unclassifiable statement at (1)
test.f90:5.4:
do i(2) = 1, 3
1
Error: Unclassifiable statement at (1)
test.f90:8.7:
end do
1
Error: Expecting END PROGRAM statement at (1)
test.f90:9.7:
end do
1
Error: Expecting END PROGRAM statement at (1)
最佳答案
对不起,我的第一个错误答案。
该限制遵循语言规则:
Fortran 2008 (ISO/IEC 1539-1:2010) 8.1.6.2:
R818 loop-control is, do-variable = ...
R819 do-variable is, scalar-int-variable-name
C812 (R819) The do-variable shall be a variable of type integer.
因此,是的,在循环控制变量的位置只允许使用标量变量名称。
如果你问为什么语言的规则是这样的,你必须问标准的作者,SC22/WG5 和 X3J3,但我猜这与固定源形式的句法无歧义的必要性有关。在固定源格式中,空格并不重要,很难提出明确的语法。
关于fortran - 在fortran中使用数组成员作为do循环的控制变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26602395/