What happens to unused function return values?

后端 未结 7 1591
太阳男子
太阳男子 2020-12-10 16:48

If I have a program:

#include 

using namespace std;

int TestIntReturn(int &x, int &y)
{
    x = 1000;
    y = 1000;
    return x+y;         


        
相关标签:
7条回答
  • 2020-12-10 17:12

    Nothing - it goes into the ether, and is not stored/used. The return value itself is an rvalue or temporary; I believe the compiler will optimize even the temporary creation out due to it not actually being used.

    0 讨论(0)
  • 2020-12-10 17:17

    The return value simply gets discarded. Depending on the exact scenario the optimizer might decide to optimize away the whole function call if there are no observable side effects (which is not the case in your example).

    So, upon return from TestIntReturn, the function will push the return value on the stack, the caller will then adjust the stack frame accordingly, but won't copy the returned value from the stack into any variable.

    0 讨论(0)
  • 2020-12-10 17:20

    The return value is stored on the stack and popped off when the function returns. Since it is not being assigned to a variable by the caller, it is just discarded when the stack is popped.

    0 讨论(0)
  • 2020-12-10 17:21

    It is discarded; the expression TestInReturn(a,b) is a discarded-value expression. Discarding an int has no effect, but discarding a volatile int (or any other volatile-qualified type) can have the effect of reading from memory.

    0 讨论(0)
  • 2020-12-10 17:31

    Since you're talking about Windows, we'll assume an x86 processor.

    In this case, the return value will typically be in register EAX. Since you're not using it, that value will simply be ignored, and overwritten the next time some code that happens to write something into EAX executes.

    In a fair number of cases, if a function has no other side effects (just takes inputs and returns some result) the compiler will be able to figure out when you're not using the result, and simply not call the function.

    In your case, the function has some side effects, so it has to carry out those side effects, but may well elide code to compute the sum. Even if it wasn't elided, it can probably figure out that what's being added are really two constants, so it won't do an actual computation of the result at run-time in any case, just do something like mov EAX, 2000 to produce the return value.

    0 讨论(0)
  • 2020-12-10 17:33

    Everybody answered correctly - the return value in this case is simply discarded, and in this specific example, you can ignore it.

    However, if the return value is a pointer to memory allocated inside the function, and you ignore it, you'll have a memory leak.

    So some function values you can't just ignore, but in this case - you can.

    0 讨论(0)
提交回复
热议问题