首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 到 IL 深度解析:第3章 選擇與循環 (11) - do-while 與 while 循環的 IL 差異

     編輯:關於C語言

do-while 與 while 的條件檢查時機

  • do-while:條件在循環結尾檢查,循環體至少執行一次。
  • while:條件在循環開頭檢查,循環體可能從未執行。

IL 實現對比

以下程式分別使用 while 與 do-while 輸出 12 兩次,總輸出 1212:

// C# 代碼
public class zzz {
    public static void Main() {
        int i;
        i = 1;
        while (i <= 2) {
            System.Console.Write(i);
            i++;
        }
        i = 1;
        do {
            System.Console.Write(i);
            i++;
        } while (i <= 2);
    }
}

while 循環 IL:先 br.s IL_000e 跳到條件檢查(ble.s IL_0004),符合才進入循環體 IL_0004。

do-while 循環 IL:直接執行循環體(IL_0014 起始),最後才以 ble.s IL_0014 檢查條件決定是否回跳。

.method public hidebysig static void vijay() il managed {
    .entrypoint
    .locals (int32 V_0)
    // while 部分
    ldc.i4.1
    stloc.0
    br.s IL_000e
    IL_0004: ldloc.0
    call void [mscorlib]System.Console::Write(int32)
    ldloc.0
    ldc.i4.1
    add
    stloc.0
    IL_000e: ldloc.0
    ldc.i4.2
    ble.s IL_0004
    // do-while 部分
    ldc.i4.1
    stloc.0
    IL_0014: ldloc.0
    call void [mscorlib]System.Console::Write(int32)
    ldloc.0
    ldc.i4.1
    add
    stloc.0
    ldloc.0
    ldc.i4.2
    ble.s IL_0014
    ret
}

結論

在 IL 中撰寫 do-while 比 while 更直觀,因為條件判斷自然置於循環末尾,無需額外的無條件跳轉去檢查初始條件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved