This is just to clarify some confusions that I've had for quite a while in C/C++: if my understanding is correct...is it true that in C/C++ you can return a local struct by value (copy) from a function, but not a local array? For example (my understanding of events has been stated in the comments with ?
indicating an assertion I'm not entirely confident of making):
#include <stdio.h>
struct my_structure { int x; int y; };
struct my_structure foo(int a, int b)
{
// declare struct variable (will allocate 4 + 4 bytes on foo()'s stack frame for 2 ints)
struct my_structure ms;
// do some kind of processing on the struct variable; just for example, let's say...
ms.x = a*a;
ms.y = b*b;
// ? return by value: will COPY the 4 + 4 bytes into caller (main)
return ms;
}
int main() {
struct my_structure retval; // will allocate 4 + 4 bytes on the main()'s stack frame
retval = foo(10, 20); // ? will copy foo()'s local struct `ms` into the 4 + 4 bytes allocated in above declaration
printf("%d, %d\n", retval.x, retval.y); // 100, 400
}
If I'm not wrong, in the above code sample, there is no question of returning any kind of an address---everything is being dealt with purely in terms of values and copying, so returning structs this way should be safe, although not efficient for large structs.
Now coming to function-local arrays, I have gone through some posts (such as this) saying that you cannot return a local array from a function. What I want to know is the reason why you cant just copy the array values byte-wise like you can with structs from the called function's stack to the caller's (as in the above code example)?
This is my guess: when you return an array by name, the C/C++ compiler implicitly converts the name to a pointer to the first element (array to pointer decay?) so instead of returning a copy you end up returning the base address to an array which, when the variable goes out of scope, won't point to anything (this is very bad and thus should not be done). This is not the case with structs, where returning a struct variable by name, simply returns the struct variable as a copy (no decaying to pointer whatsoever). Am I correct or is my understanding flawed? Any suggestions are welcome. Thank you.
EDIT: MY question is mostly aimed at C, but because C++ is supposed to be a superset, I'm assuming it would apply to C++ as well?