30
Apr

When you return values in C/C , does this work in the same way as Pass by Value in that it duplicates the value? Or is it more like Pass by Reference, where it doesn't use up any extra memory?

Thank you to anyone who answers :)


Answer:
You're going to be storing the return value into a variable, so you must already have reserved some space for that. (Let's assume it's an int and you're on a 32-bit system, so it will be 4 bytes.)

But you probably also declared a local variable within the function to use for the return value, so you’ll have reserved some space for that as well — another 4 bytes. But that probably will be taken from the stack rather than the heap, and so will become available again when the function exits.

If you were canny and just had a “return” line within your function (no local variables at all) then you would definitely only be using stack space. Using round brackets to force the order of operations also takes up stack space, to store the intermediate results.

But it depends ultimately on the compiler implementation.

Unless this is an embedded application where you’ve to make each byte count, I wouldn't worry too much about it.


Answer:
Return variables go onto the stack. As soon as a function finishes the value is on the stack. When the function ends the value will be gone too. You can grab the value by assigning the result to a variable but the return value will not persist.

Book Mark it-> del.icio.us | Reddit | Slashdot | Digg | Facebook | Technorati | Google | StumbleUpon | Window Live | Tailrank | Furl | Netscape | Yahoo | BlinkList

This entry was posted on Wednesday, April 30th, 2008 at 2:29 pm and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or TrackBack URI from your own site.

Leave a reply

Name (*)
Mail (*)
URI
Comment