Paulo Flabiano Smorigo wrote:
- It's a true structure return or something else?
That may depend on what you mean by "true structure return".
The practical way to "return a structure" is for the compiler to make
the calling code allocate the space and pass in a pointer to that space,
so the actual implemented function has one more input that the explicit
ones.
Returning a tiny structure may be more practical by putting the entire
structure in the registers used for return values.
Both of those and potentially other methods ought to be in your
definition of "true structure return". If you have some narrower view
of what "true structure return" means, then maybe C doesn't use a "true
structure return".
myStruct getMyStruct()
{
myStruct sample;
printf("sample: %x\n", (unsigned int)&sample);
sample.a = 5;
sample.b = 6;
sample.c = 7;
return sample;
As written, the code implies a copy from the local structure declared
inside this function to whatever form the temporary object being
returned might take (probably allocated in the caller with its address
passed in as a hidden parameter).
I would hope the optimizer could work backwards from the return
operation, to realize that the return temporary can be used in place of
the local object, so the local object doesn't need to be allocated and
no copy is needed for the return.
I don't actually know when or if the optimizer can figure that out.
I don't know if your printf of the object address would reveal that the
optimizer did that or if it would stop the optimizer from doing that.
myStr = getMyStruct();
Similarly, the code as written implies a second copy operation from the
return temporary to the object local to main().
Again, I hope the optimizer can see this common construct and (assuming
an object return is implemented as a hidden address passed in) pass the
address of myStr and never do the copy.
Whether the compiler does that or not, your test of whether the address
of myStr changes is not meaningful. I can't see how that address might
change anyway, but the fact that you printf that address makes it
illegal for the optimizer to change it.
I don't know when the optimizer might get rid of one or both of the copy
operations implied by your original code.
Maybe I ought to understand this topic better and know what the compiler
will do. But in my own code, if I care whether those copies are
eliminated (and I usually do) then I explicitly code what I would have
hoped the optimizer would do for me. I pass the result address in as an
explicit argument, rather than returning a structure by value and
trusting the compiler to fix that inefficiency.
If you care about just the function and not the performance, then you
clearly can trust the compiler to do something that has the correct
result for a return by value of a structure.