I have the following code.
struct rectangle {
int length;
int breadth;
};
int main (void)
{
struct rectangle a,b;
a.length = 10;
a.breadth = 5;
b=a;
printf("\nValues of b.length = %d, b.breadth=%d\n",b.length,b.breadth);
return 0;
}
Is the above assignment a valid statement?(b=a) I did it this way inside my project. I got a review comment stating, this type of assignment is wrong and i should have done used memcpy. I printed the values of b and checked. The values are correct. I was wondering why the above assignment is wrong? If it is wrong what happens when you pass a structure variable to a function and catch it in a separate variable? I hope i am clear on my question. Please get back to me if i am unclear on my question.
The reviewer is, in my opinion, misguided. It’s very correct, struct values are just like any other, it’s just fine to assign them. And it’s way, way, clearer than invoking
memcpy(), and much (much!) less error-prone.I always have to stop and think about what to pass as the third argument to
memcpy()when copying the same type of value, since I find it non-obvious which choice is the clearest. So, that’s one less pedagogical problem, and of course it just reads better.Also, the compiler might be smart enough not to copy any additional padding and/or alignment bytes that might lurk in there, something
memcpy()can never do. It’s a higher-level construct, and thus “simply better”.