正如其他人已经指出的那样,答案是循环不会进入第 5 次迭代,因为您示例中的 [stop-] 条件是“
您可能会发现the MS docs about it 很有帮助。摘录如下:
for(初始化器;条件;迭代器)
body
初始化部分设置初始条件。本节中的语句只运行一次,在您进入循环之前。该部分只能包含以下两个选项之一。
条件部分包含一个布尔表达式,用于确定循环是应该退出还是应该再次运行。
迭代器部分定义了循环体每次迭代后发生的情况。迭代器部分包含零个或多个 [...] 语句表达式,以逗号 [...]
分隔
作为旁注,可能值得一提的是,用于关系测试的运算符(如 '
C# language specification - ECMA-334 在“12.3.3.9 For statements”中显示了非常清晰的定义,这也解释了 for 循环
for (int i = 2; i < 10; i += 2)
{
sum += i;
}
可以翻译成while循环
int sum = 0;
int i = 2;
while (i < 10)
{
sum += i;
i += 2;
}
这使得指令的顺序更加明显。
使用ildasm,除了一些NOP指令外,两个循环的输出是相同的。这是一个带注释的版本:
.method private hidebysig static void Testloop() cil managed
{
// Code size 27 (0x1b)
.maxstack 2
.locals init ([0] int32 sum, <-- this is location 0 --> 1. int sum = 0;
[1] int32 i, <-- this is location 1 --> 2. int i = 2;
[2] bool CS$4$0000) <-- this is location 2 --> 3. unnamed temporary result storage for the i < 10 comparison
IL_0000: nop --> no operation is the machine code equivalent of a space character and can be ignored
IL_0001: ldc.i4.0 --> 1. int sum = 0;
IL_0002: stloc.0 --> 1.
IL_0003: ldc.i4.2 --> 2. int i = 2;
IL_0004: stloc.1 --> 2.
IL_0005: br.s IL_0011 --> branch to target IL_0011, which is a "goto" and jumps over the conditional check and iterator code which starts at IL_0007
IL_0007: nop --> no operation is the machine code equivalent of a space character and can be ignored
IL_0008: ldloc.0 --> 5. sum += i
IL_0009: ldloc.1 --> 5.
IL_000a: add --> 5.
IL_000b: stloc.0 --> 5.
IL_000c: nop --> no operation is the machine code equivalent of a space character and can be ignored
IL_000d: ldloc.1 --> 6. i += 2
IL_000e: ldc.i4.2 --> 6.
IL_000f: add --> 6.
IL_0010: stloc.1 --> 6.
IL_0011: ldloc.1 --> 3. i < 10
IL_0012: ldc.i4.s 10 --> 3.
IL_0014: clt --> 3.
IL_0016: stloc.2 --> 4. continue until ( 3. ) is true (meaning, i >= 10) by jumping back to the start at IL_0007
IL_0017: ldloc.2 --> 4.
IL_0018: brtrue.s IL_0007 --> 4.
IL_001a: ret --> the closing bracket of the method Testloop()
} // end of method Program::Testloop