以下程式分別使用 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 更直觀,因為條件判斷自然置於循環末尾,無需額外的無條件跳轉去檢查初始條件。