2014-08-28 49 views
4

Fortran 90和更高版本強烈建議不要使用goto聲明。我們是否可以在所有情況下確實避免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 

情況2 - 若要註釋程序(相當於在/* ... */ C)的一個大的連續的部分。例如,

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

如何才能擺脫使用goto聲明和使用上述兩種情況下,一些替代品的Fortran 90的?

+0

要從理論角度回答標題問題:[Böhm-Jacopini定理](https://en.wikipedia.org/wiki/Structured_program_theorem) – 2014-08-29 11:37:24

回答

3

案例1

你有什麼是無限循環,循環,直到滿足條件。可以使用塊。


案例2

非Fortran的答案是:use your editor/IDE's block comment tool to do this

在Fortran中,這樣的流動控制可以是

if (i_dont_want_to_skip) then 
    ! Lots of printing 
end if 

或(這是不Fortran 90中)

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

但是,這並不是說所有的goto S的關係要避免,即使很多/全部都可以。

+2

另一種可能性案例2將使用預處理器指令。 – PetrH 2014-08-28 20:17:08

+1

的確,好點。雖然我把它作爲非Fortran的方式,它將非常像'if'構造。 – francescalus 2014-08-28 20:40:04

0

根據你所說的情況2「計劃的連續部分」什麼可以跳一些塊結構,如:

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

     1  continue 

如果你遇到這樣的事情也可以是相當大的挑戰解開代碼邏輯並用現代結構化編碼取代。更有理由不以這種方式「評論」。

+0

謝謝大家的討論。 @PetrH,你能否詳細說明「預處理指令」的含義? – hbaromega 2014-08-30 14:25:21

相關問題