编译器如何用postfix操作符处理返回语句?(How does compiler handle return statement with postfix operator?)

系统教程 行业动态 更新时间:2024-06-14 17:01:34
编译器如何用postfix操作符处理返回语句?(How does compiler handle return statement with postfix operator?)

有人可以解释以下代码的工作原理吗?

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::index

loads the value of index onto the evaluation stack - stack contains 6.

L_0005: dup

duplicates the value on the top of the stack - stack contains 6, 6

L_0006: ldc.i4.1

loads the value 1 onto the stack - stack contains 6, 6, 1

L_0007: add

adds 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::index

Stores the top value on the stack into index. index now equals 7, stack contains 6.

L_000d: ret

Takes the top value on the stack (6) as the return value.

更多推荐

本文发布于:2023-04-20 18:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/d1d41bbab29bb19ee22a8cfffdd10e59.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:编译器   如何用   语句   操作   postfix

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!