Message from discussion
Expert-Q: (a!=b) != memcmp(&a,&b,sizeof a) ?
From: usur...@euronet.nl (Paul Mesken)
Subject: Re: Expert-Q: (a!=b) != memcmp(&a,&b,sizeof a) ?
Date: 1999/06/28
Message-ID: <377b53ef.5062366@news.euronet.nl>#1/1
X-Deja-AN: 494732264
Content-Transfer-Encoding: 7bit
References: <377738B4.97C7C3D@hls.via.at>
Organization: Not currently
Content-Type: text/plain; charset=us-ascii
Mime-Version: 1.0
Newsgroups: comp.lang.c
On Mon, 28 Jun 1999 10:56:20 +0200, Helmut Leitner
<leit...@hls.via.at> wrote:
>Let's assume that a and b have the same basic data type
>(e.g. int, long, float, double ...).
>
>On many platforms it is possible to replace the
>comparisions
> a==b
> a!=b
>by
> memcmp(&a,&b,sizeof(a))==0
> memcmp(&a,&b,sizeof(a))
>
If a and b are of the same basic data type then you wouldn't do this.
It's ugly and probably slower. Besides: what if a and/or b have the
storage class specifier "register"? Then it is illegal to use the
address-of operator on them.
>What are the conditions that this will not yield the
>desired results?
>
If they are not of the same basic type for example. Unlike using the
equality operators, the memcmp version will not convert them. This
might result in inequality while the values of a and b are the same.
It might look as if the memcmp version can do "clever" comparisons
since it would also accept derived types like structures but even if a
and b are of the same derived type you would still run the risk of
inequality in the case of inequal values in the padding (if any).
Thus, inequality might even appear for structures that are of the same
type and have the same values for their members.
However:
>The background is the wish of fast and easy comparison
>of multicomponent structures (within a perfect hash system):
>
> typedef struct test {
> char ...
> int ...
> float ...
> ...
> } TEST;
>
> TEST sa,sb;
> memset(&sa,'\0',sizeof(TEST)); /* or TestClear(&sa); */
> memset(&sb,'\0',sizeof(TEST)); /* or TestClear(&sb); */
> ...
> any standard component assignment. /* or TestSetComponent(&sa,comp) */
> ...
> memcmp(&sa,&sb,sizeof(TEST));
>
Yes, you first set all char's of the structures to zero. This solves
the problem of the "uninitialized padding".
>Is it possible to construct such a general system to work
>in a portable way on all platforms?
>
In this particular case I don't see why not.
>Would it be possible to construct an #if-expression
>
> #if (expression_memcmp_will_do_the_job)
> TestEqu(psa,psb) (memcmp(psa,psb,sizeof(TEST))==0)
> #else
> (psa->comp1==psb->comp2 && psa->comp2==psb->comp2 && .... )
> #endif
>
>to react to the different situations?
I don't see how the expression should look like. Your solution works
as long as you take care to initialize _all_ char's of the structures
to avoid the "inequal padding value" problem and make sure that your a
and b are of the same structure type.