Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a non-void function without using its return value. What actually happens?

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

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.

like image 334
DomenicDatti Avatar asked Oct 22 '10 15:10

DomenicDatti


People also ask

When a function does not return a value we call it a void function?

The void functions are called void because they do not return anything. “A void function cannot return anything” this statement is not always true. From a void function, we cannot return any values, but we can return something other than values.

What happens if you forget the return statement in a non void function?

If control reaches the closing curly brace ( } ) of a non- void function without evaluating a return statement, using the return value of the function call is undefined behavior.

What happens if you call a function that has a return value but you don't save the return value in a variable?

nothing, the return value gets ignored.

What would happen when calling a function that has no return statement?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.


1 Answers

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.

For example, consider the following C# code:

using System;

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

The IL generated (by the MS C# 4 compiler) for the Main method is:

.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 
}

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

like image 72
Jon Skeet Avatar answered Oct 07 '22 00:10

Jon Skeet