I am aware that in C you can pass (or return) a structure by value but you cannot pass an array by value. What happens when the structure contains an array? Will the array (that is within the structure) be copied as the structure is passed (or returned) by value? I have run a sample at ideone.com and it works, but I would like to know where in the standard this is covered (and yes, I have looked).
http://open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf
typedef struct
{
float aValue;
int anArray[5];
} myStruct;
myStruct addValueToArray(myStruct in)
{
myStruct out = in;
int i;
for (i = 0; i < 5; i++)
{
out.anArray[i] = in.anArray[i] + in.aValue;
}
return out;
}
Yes, it will be copied. The entire structure is a value, so it can be passed to a function, returned, and (many seem to forget this but you use it, good!) assigned.
Note that any padding that might be present need not be copied, which makes it possible for
=to be faster than a manual call tomemcpy()could be, since it can never do that.Quite hard to find a single place in the PDF that supports this, but I’m not very experienced in looking. Basically,
structinstances are “values” in C’s sense, so most of the talk just automatically coversstructs.Like: