调用非void函数不使用它的返回值。到底发生了什么? [英] Calling a non-void function without using its return value. What actually happens?

查看:397
本文介绍了调用非void函数不使用它的返回值。到底发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我发现了一个类似的问题这里,但答案是更多的风格,你是否是能够做到这一点。

So, I found a similar question here, but the answers are more about style and whether or not you are able to do it.

我的问题是,当你调用一个实际发生的事情非void函数返回一个对象,但你永远不分配或使用表示返回的对象?所以,少谈你是否可以,因为我绝对知道你可以和理解上面链接的另一个问题......是什么编译/运行环境呢?

My question is, what actually happens when you call a non-void function that returns an object, but you never assign or use said returned object? So, less about whether or not you can, because I absolutely know you can and understand the other question linked above... what does the compiler/runtime environment do?

这是不是一种语言的具体问题,但如果你回答,请注明你指的是什么语言,因为行为会有所不同。

This is not a language specific question, but if you answer, please specify what language you are referring to, since behaviors will differ.

推荐答案

我相信,无论对于C#和Java,结果在堆栈中结束,然后编译器会强制弹出指令忽略它。埃里克利珀对博客文章虚空是不变的< 。/ A>有一些这方面的更多信息。

I believe that for both C# and Java, the result ends up on the stack, and the compiler then forces a pop instruction to ignore it. Eric Lippert's blog post on "The void is invariant" has some more information on this.

例如,请考虑下面的C#代码:

For example, consider the following C# code:

using System;

public class Test 
{
    static int Foo() { return 10; }

    public static void Main()
    {
        Foo();
        Foo();
    }
}



生成的IL(由MS C#4编译)为方法是:

.method public hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 8
    L_0000: call int32 Test::Foo()
    L_0005: pop 
    L_0006: call int32 Test::Foo()
    L_000b: pop 
    L_000c: ret 
}

请注意来电来弹出 - 如果你让一个void方法,它消失

Note the calls to pop - which disappear if you make Foo a void method.

这篇关于调用非void函数不使用它的返回值。到底发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆