Skip to main content

This is documentation for Caché & Ensemble. See the InterSystems IRIS version of this content.Opens in a new tab

For information on migrating to InterSystems IRISOpens in a new tab, see Why Migrate to InterSystems IRIS?

For 文と Do/While 文と While 文

これまで $Order ループの例として Do/WhileWhile 文に対し、引数を持たない For 文を参照しました。For には他のループにはない、いくつかの利点があります。詳細は "For 文 (2)" を参照してください。復習後、ブラウザの [戻る] ボタンを使用すると学習を継続できます。

For 文は、ループの終了を最初 (While) や最後 (Do/While) に置く文と異なり、繰り返しコードにループを終了させる条件を置くことができます。これにより、For の条件チェックは 1 度のみです。その他の条件チェックは 2 度あります。以下は、コード・サンプルの例です。

compareloop ; different styles of looping
            /* the first three loops are logically equivalent,
                 but the 1st is recommended over the 2nd and 3rd versions.
               the 4th loop is a copy of the third loop,
                 but without the internal quit, so there's a logical error. */
usefor write !, "Using For"
    for  
        {
        set x = $random(10)
        quit:(x = 5)  // this quit ends the code block AND terminates the loop
        write !, x
        }
        
usewhile write !!, "Using While"
    set x = ""
    while x '= 5 // this condition is evaluated each time, for no reason
        {
        set x = $random(10)
        quit:(x = 5)  // this quit ends the code block AND terminates the loop
        write !, x
        }
        
usedo write !!, "Using Do/While"
    do 
        {
        set x = $random(10)
        quit:(x = 5)  // this quit ends the code block AND terminates the loop
        write !, x
        }
    while x '= 5 // this condition is evaluated each time, for no reason
    
badusedo write !!, "Using Do/While, but it writes the terminating 5"
    do 
        {
        set x = $random(10)
        write !, x
        }
    while x '= 5 // this condition terminates the loop (a little too late)
FeedbackOpens in a new tab