Reputation: 1020
I recently found out that structure assignment in C was as simple as a=b(I was using memcpy/memmove/custom functions so long). My question is that: Are two objects of a same structure always guaranteed to have the same padding to make a=b work blindly?
Upvotes: 1
Views: 113
Reputation: 119867
The C standard places some conditions on the assignment operator, one of which must hold. This is one of the condition
the left operand has an atomic, qualified, or unqualified version of a structure or union type compatible with the type of the right
Any type is compatible with itself.
The standard further says
the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.
A conversion from any type to itself is a no-op.
So your assignment is guaranteed to work and have the obvious effect. One doesn't have to appeal to sizes, alignments, or paddings.
Upvotes: 0
Reputation: 222900
In section 6.2.6, the C standard (draft N1570) discusses how types are represented. Clause 6.2.6.1, paragraph 4 says: “Values stored in non-bit-field objects of any other object type consist of n × CHAR_BIT bits, where n is the size of an object of that type, in bytes.”
The clear implication here is that, for any one type, there is an n that is the number of bytes used to represent objects of that type. So two different structures of the same type would have the same number of bytes.
That addresses the total number of bytes. We might also consider whether two structures might have some different internal arrangement of padding bytes.
6.25 20 says: “A structure type describes a sequentially allocated nonempty set of member objects (and, in certain circumstances, an incomplete array), each of which has an optionally specified name and possibly distinct type.” So we see that a structure is intended to be composed of separate objects. In 7.19 3, the standard defines an offsetof
maxro that takes the names of a type and a member and evaluates to the offset of the member within the type. Since this uses the type, not a particular object of the type, the offset must be the same for all objects of the type. Therefore, all members of a structure have the same locations in all instances of objects of the structure.
Upvotes: 1