Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to unused function return values?

If I have a program:

#include <iostream>

using namespace std;

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

int main()
{
    int a = 1;
    int b = 2;
    cout << a << " " << b << endl;
    TestIntReturn(a,b);
    cout << a << " " << b << endl;
}

what happens to the return value of TestInReturn(a,b) since it is unused?

like image 270
xcdemon05 Avatar asked Feb 26 '13 18:02

xcdemon05


2 Answers

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.

like image 173
Jerry Coffin Avatar answered Sep 25 '22 12:09

Jerry Coffin


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.

like image 25
ecatmur Avatar answered Sep 22 '22 12:09

ecatmur