Can we indeed avoid goto in all cases?

≯℡__Kan透↙ 提交于 2019-12-10 16:29:39

问题


Fortran 90 and later strongly recommend not to use goto statement.

However, I still feel forced to use it in either of the two cases:

Case 1 -- Instruct to re-enter the input value, e.g.

      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

Case 2 -- To comment a large continuous part of a program (an equivalent to /* ... */ in C). Eg.

       print*,'This is to printed'
       goto 50
       print*,'Blah'
       print*,'Blah Blah'
       print*,'Blah Blah Blah'   
 50    continue
       print*,'Blahs not printed'

How can I get rid of using goto statement and use some alternatives in the above two cases in Fortran 90?


回答1:


Case 1

What you have is an indefinite loop, looping until a condition is met.

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

Or one could use a do while lump.


Case 2

A non-Fortran answer is: use your editor/IDE's block comment tool to do this.

In Fortran, such flow control can be

if (i_dont_want_to_skip) then
  ! Lots of printing
end if

or (which isn't Fortran 90)

printing_block: block
  if (i_do_want_to_skip) exit printing_block
  ! Lots of printing
end block printing_block

But that isn't to say that all gotos should be avoided, even when many/all can be.




回答2:


depending on what you mean by "continuous part of a program" case 2 could be jumping out of some block structure, eg:

             do i = 1,n
                  ...
                  goto 1
                  ...
             enddo
              ...

        1      continue

If you encounter such thing it can be quite a challenge to unravel the code logic and replace with modern structured coding. All the more reason not to "comment" that way..



来源:https://stackoverflow.com/questions/25553892/can-we-indeed-avoid-goto-in-all-cases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!