writes:
>>> Q: I need to copy and compare C Structs.
>>>
>>> Is this the safe and quick way to do it?:
> sniip
>>
>>
>>Copying is easy: new = old;
> As the comapre (new == old) made the compiler unhappy I didn't want to
> trust the assign (old = new).
>>
>>For safe and meaningful comparison, compare on a field-by-field basis,
>>comparing the most significant fields first. Typically one would write
>>a function to do this.
> Well once I've found a change I do have to go through each field to
> and action the changes. However the changes are rare, so I wanted to
> get the 'compare' over and done with asap, hence the 'old == new' as
> there can be quite a few fields in the structure (20+ at the mo).
>
>>It is not sweet -- the advice is wrong (except in the oddest of
>>situations). It is entirely possible for memcmp to return non-zero
>>when the two structures are equal in all important respects (i.e. have
>>identical values in all members).
> Well I have an odd situation because it has worked for me. Can you (if
> you have the time and inclination) tell me why memcmp would do this
> (is it because of 'structure' padding/alignment and that two
> 'identical' structs not being identical)? I was concerned (hence the
> question in the 1st place).
Yes, the problem is (mostly) structure padding. If you are certain
the there is none (on all the platforms you can foresee) or that you
have set to some known value in every case (because you have used
memset always) then you might me able to get away with it, but it
seems to me you would be making a fragile solution.
There is another sort of padding internal to some types that the
standard allows. Hence one can not assume that two values that
compare equal will be equal as far as memcmp is concerned.
Finally, some types have their own notion of equality that need not be
byte-for-byte equality. This is most obvious for floating point types
but it is also possible that two pointers might be == but have distinct
representations. Similarly, when a type permits trap representations,
the effect of == and memcmp may be different (but in this case the
memcmp will succeed in a possibly deceptive way).
BTW, it is probably not a good idea to join two answers together like
this. For one thing you can't easily keep the attribution lines (you
should have kept them, in my opinion).
--
Ben.