Yesterday, I found myself writing code like this:
SomeStruct getSomeStruct() { SomeStruct input; cin >> input.x; cin >> input.y; }
Of course forgetting to actually return the struct I just created. Oddly enough, the values in the struct that was returned by this function got initialized to zero (when compiled using g++ that is). Is this just a coincidence or did another SomeStruct get created and initialized somewhere implicitly?
Think about how the struct is returned. If both
xandyare 32 bits, it is too big to fit in a register on a 32-bit architecture, and the same applies to 64-bit values on a 64-bit architecture (@Denton Gentry’s answer mentions how simpler values are returned), so it has to be allocated somewhere. It would be wasteful to use the heap for this, so it has to be allocated on the stack. But it cannot be on the stack frame of yourgetSomeStructfunction, since that is not valid anymore after the function returns.The compiler instead has the caller tells the called function where to put the result (which is probably somewhere on the stack of the caller), by passing the called function a hidden pointer to the space allocated to it. So, the place where it is being set to zero is on the caller, not on your
getSomeStructfunction.There are also optimizations like the ‘named value return optimization’ where extra copies can be elided. So, had you used the missing
return, the result would be created directly on the space allocated by the caller, instead of creating a temporary and copying it.To know more about what is happening, you have to look at the caller function. Is it initializing (to zero) an ’empty’
SomeStructto which you later assign the return value of yourgetSomeStructfunction? Or is it doing something else?