I\'m a computer science college student. Yesterday, I have a class about Binary Search Tree using C++. We are taught by lab assistants in that class.
They define the nod
Typically, you've got one hardware register used to return value from a function (that'd be %EAX on i686, for instance). If the last thing you did in your function is calling another function and the intended return value is the result of that function, it may occur that %EAX value hasn't been trashed and is nicely retrieved by the caller.
That's subject to many hypothesis, however, and you shouldn't expect it to be reliable in any way. First of all, the compiler can detect that you're not using the return value of search()
, so it might decide to optimize away that call if it has hints about search()
having no side effects. If it's capable of inlining the search call, it could partly optimize it away.
There may be other architectures (iirc, that'd be the case with IA64) where the calling convention are more subtle, and where the registers used for returning values in one function are not the same as in the caller function. So your code relies on platform-dependent details to be working while it's supposed to be a high-level (and portable) language.
It's just undefined behavior.
It appears to work because there's one register that holds the return value. In the deepest paths of the recursion tree, the temp
is moved into that register, and never cleared or changed afterwards, so that register will contain the correct node until the first call returns.
When the first call returns, the calling context checks that register for the return value, which happens to be correct. But you shouldn't rely on this. It's not safe to assume it will always work.