Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

c++ - What happens to the return value if I don't store it anywhere?

In the small sample below:

#include<iostream>
using namespace std;

int z(){
    return 5 + 10; // returns 15
}

int main(){
    z(); // what happens to this return?
    cout << "Did not fail";
    return 0;
}

What happens to the 15? I tried running it in debugger but I can't find it anywhere. I assume that because it didn't get assigned to anything it just vanished but I feel like that's wrong.

I asked my TA about this today and he told me it's stored on the call stack but when I viewed it in debugger I see that it is not.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The C++ standard imposes the "as-if" rule. That rule means that a C++ compiler can do anything to a program as long as all side effects (inputs and outputs that are visible to the rest of the system, like writing to a file or showing stuff on the screen) are respected. Going back to my cheeky philosophical comment, this means that in C++, when a tree falls in the forest and no one is there to hear it, it doesn't have to make a sound (but it can).

In the case of your program, at a high level, since your function does nothing, the compiler may or may not create a call to it, or could even remove it from the compiled binary. If it does include and call it, the return value will go to whatever return slot your platform's application binary interface specifies. On almost every x86_64 system, that will be the rax register for an integer return value. The return value is there but will never be read and will be overwritten at some point.

If it was a non-trivial object instead of an int, its destructor would be invoked immediately.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...