Re: Struct compares/copies
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Sat, 16 Jun 2007 17:43:58 +0100
bb@xxxxxxx writes:
sniipQ: I need to copy and compare C Structs.
Is this the safe and quick way to do it?:
As the comapre (new == old) made the compiler unhappy I didn't want to
Copying is easy: new = old;
trust the assign (old = new).
Well once I've found a change I do have to go through each field to
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.
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 ofWell I have an odd situation because it has worked for me. Can you (if
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).
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.
.
- References:
- Struct compares/copies
- From: bb
- Re: Struct compares/copies
- From: Richard Heathfield
- Re: Struct compares/copies
- From: bb
- Struct compares/copies
- Prev by Date: Re: how the following code works?
- Next by Date: Re: Struct compares/copies
- Previous by thread: Re: Struct compares/copies
- Next by thread: Re: Struct compares/copies
- Index(es):
Relevant Pages
|