Tutorial :function return not assigned to a variable



Question:

What if you call a (non-void) function, but don't assign its return value to a variable? e.g., getchar();

I've always wondered what happens to such a value. I've heard humorous explanations like "its gone to the ether" and so forth, but I'd really like to know really. Would there be any way to recover such a value? Thanks


Solution:1

This is really compiler / CPU specific, but in most cases the return value will be in a CPU register (if it will fit), and if that register is not touched by the subsequent code, you could retrieve it using e.g. "inline assembler".

To answer your question better, nothing "happens" to the value. It sits in a stack-location or inside a register. If you use it, fine... if not, nothing happens really. Eventually the stack or register is overwritten by new values...


Solution:2

No, you won't.

The value gets popped off the stack and is gone.

If you need the return value, you should assign it to a variable.


Solution:3

Simply 'returning' (either by implicitly calling return by itself or not returning at all) and not assigning a value does just that, doesn't assign a value and thus is null.


Solution:4

If you want to learn more about how it all works, you can look at this: http://en.wikipedia.org/wiki/Call_stack


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »