Can we indeed avoid goto in all cases?

2019-06-27 04:11发布

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?

2条回答
趁早两清
2楼-- · 2019-06-27 04:29

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.

查看更多
叼着烟拽天下
3楼-- · 2019-06-27 04:30

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..

查看更多
登录 后发表回答