Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we indeed avoid goto in all cases?

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?

like image 545
hbaromega Avatar asked Oct 01 '22 00:10

hbaromega


1 Answers

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.

like image 62
francescalus Avatar answered Oct 05 '22 05:10

francescalus