I'm not a C programmer by trade but I've been getting more interested recently. As I understand it, in C function arguments are passed by value so that explains why v1 is unchanged.
The thing I don't understand is why v2 has the correct value after the stack_copy returns. My understanding is that function args are put on the stack and should be dealloacted at the end of of the function scope and so I would expect v2 to contain junk.
What's going on here?
Note: I tested this in c using the Visual Studio 2015 compiler on Windows and clang on OSX.
#include "assert.h"
typedef struct {
int x;
int y;
int z;
} Vec3;
Vec3 stack_copy(Vec3 v) {
v.x = 3;
v.y = 3;
v.z = 3;
return v;
}
int main() {
Vec3 v1 = {7, 7, 7 };
Vec3 v2 = stack_copy(v1);
assert(v1.x == 7 && v1.y == 7 && v1.z == 7);
assert(v2.x == 3 && v2.y == 3 && v2.z == 3);
return 0;
}