我们真的可以在所有情况下都避免 goto 吗?

hba*_*ega 5 fortran goto fortran90

Fortran 90 及更高版本强烈建议不要使用goto语句。

但是,我仍然觉得必须在以下两种情况下使用它:

情况 1 -- 指示重新输入输入值,例如

      program reenter   
10    print*,'Enter a positive number'
      read*, n

      if (n < 0) then
      print*,'The number is negative!'
      goto 10
      end if

      print*,'Root of the given number',sqrt(float(n))

      stop
      end program reenter
Run Code Online (Sandbox Code Playgroud)

案例 2 —— 注释程序的一个大的连续部分(相当于/* ... */C 中的)。例如。

       print*,'This is to printed'
       goto 50
       print*,'Blah'
       print*,'Blah Blah'
       print*,'Blah Blah Blah'   
 50    continue
       print*,'Blahs not printed'
Run Code Online (Sandbox Code Playgroud)

goto在 Fortran 90 中的上述两种情况下,如何摆脱 using语句并使用一些替代方案?

fra*_*lus 4

情况1

你所拥有的是一个无限循环,循环直到满足条件。

do
  read *, n
  if (n.ge.0) exit
  print *, 'The number is negative!'
end do
! Here n is not negative.
Run Code Online (Sandbox Code Playgroud)

或者可以使用一do while团。


案例2

非 Fortran 答案是:使用编辑器/IDE 的块注释工具来执行此操作

在 Fortran 中,这种流量控制可以是

if (i_dont_want_to_skip) then
  ! Lots of printing
end if
Run Code Online (Sandbox Code Playgroud)

或(不是 Fortran 90)

printing_block: block
  if (i_do_want_to_skip) exit printing_block
  ! Lots of printing
end block printing_block
Run Code Online (Sandbox Code Playgroud)

但这并不是说goto应该避免所有 s,即使可以避免 Many/all。

  • 情况 2 的另一种可能性是使用预处理器指令。 (2认同)