有人可以解释以下代码的工作原理吗?
static int index = 0; public static int GetNextIndex() { return index++; }我认为,由于增量操作发生在return语句之后,变量'index'永远不会增加。
但是,当用C#编译器测试时,我发现'索引'正在增加。
标准编译器如何处理这种情况?
Can someone explain how the following code works?
static int index = 0; public static int GetNextIndex() { return index++; }I assumed that, as the increment operation happens after the return statement, the variable 'index' will never get incremented.
But when tested with C# compiler, I observed that 'index' is getting incremented.
How does a standard compiler handle this scenario?
最满意答案
这是编译器生成的中间语言(IL)(VS2013RC / .NET 4.5.1RC):
.method public hidebysig static int32 GetNextIndex() cil managed { .maxstack 8 L_0000: ldsfld int32 ConsoleApplication4.Program::index L_0005: dup L_0006: ldc.i4.1 L_0007: add L_0008: stsfld int32 ConsoleApplication4.Program::index L_000d: ret }那么,这是做什么的? 假设在调用它之前, index的值为6。
L_0000: ldsfld int32 ConsoleApplication4.Program::index将index的值加载到评估堆栈上 - 堆栈包含6 。
L_0005: dup复制堆栈顶部的值 - 堆栈包含6, 6
L_0006: ldc.i4.1将值1加载到堆栈上 - 堆栈包含6, 6, 1
L_0007: add在堆栈中添加前两个值,并将结果放回堆栈。 堆栈包含6, 7
L_0008: stsfld int32 ConsoleApplication4.Program::index将堆栈中的最大值存储到index 。 现在index等于7 ,堆栈包含6 。
L_000d: ret将堆栈( 6 )中的最高值作为返回值。
This is the intermediate language (IL) that the compiler generates (VS2013RC/.NET 4.5.1RC):
.method public hidebysig static int32 GetNextIndex() cil managed { .maxstack 8 L_0000: ldsfld int32 ConsoleApplication4.Program::index L_0005: dup L_0006: ldc.i4.1 L_0007: add L_0008: stsfld int32 ConsoleApplication4.Program::index L_000d: ret }So, what does that do? Let's say that index has the value 6 before calling it.
L_0000: ldsfld int32 ConsoleApplication4.Program::indexloads the value of index onto the evaluation stack - stack contains 6.
L_0005: dupduplicates the value on the top of the stack - stack contains 6, 6
L_0006: ldc.i4.1loads the value 1 onto the stack - stack contains 6, 6, 1
L_0007: addadds the top two values on the stack, and places the result back on the stack. stack contains 6, 7
L_0008: stsfld int32 ConsoleApplication4.Program::indexStores the top value on the stack into index. index now equals 7, stack contains 6.
L_000d: retTakes the top value on the stack (6) as the return value.
更多推荐
发布评论