Struct assignment or memcpy? [duplicate] Struct assignment or memcpy? [duplicate] c c

Struct assignment or memcpy? [duplicate]


The struct1=struct2; notation is not only more concise, but also shorter and leaves more optimization opportunities to the compiler. The semantic meaning of = is an assignment, while memcpy just copies memory. That's a huge difference in readability as well, although memcpy does the same in this case.

Use =.


Check out this conversation about the very same topic: http://bytes.com/topic/c/answers/670947-struct-assignment

Basically, there are a lot of disagreements about the corner cases in that thread on what the struct copy would do. It's pretty clear if all the members of a struct are simple values (int, double, etc.). The confusion comes in with what happens with arrays and pointers, and padding bytes.

Everything should be pretty clear as to what happens with the memcpy, as that is a verbatim copy of every byte. This includes both absolute memory pointers, relative offsets, etc.


I'm not sure of the performance difference, although I would guess most compilers would use memcpy under the hood.

I would prefer the assignment in most cases, it is much easier to read and is much more explicit as to what the purpose is. Imagine you changed the type of either of the structs, the compiler would guide you to what changes were needed, either giving a compiler error or by using an operator= (if one exists). Whereas the second one would blindly do the copy with the possibility of causing a subtle bug.