| |
comp.lang.c |
On Mon, 28 Jun 1999 10:56:20 +0200, Helmut Leitner >On many platforms it is possible to replace the It might look as if the memcmp version can do "clever" comparisons However: > typedef struct test { > TEST sa,sb; > #if (expression_memcmp_will_do_the_job) >to react to the different situations?
>Let's assume that a and b have the same basic data type
>(e.g. int, long, float, double ...).
>comparisions
> a==b
> a!=b
>by
> memcmp(&a,&b,sizeof(a))==0
> memcmp(&a,&b,sizeof(a))
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.
>desired results?
equality operators, the memcmp version will not convert them. This
might result in inequality while the values of a and b are the same.
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.
>of multicomponent structures (within a perfect hash system):
> char ...
> int ...
> float ...
> ...
> } TEST;
> 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));
the problem of the "uninitialized padding".
>in a portable way on all platforms?
> TestEqu(psa,psb) (memcmp(psa,psb,sizeof(TEST))==0)
> #else
> (psa->comp1==psb->comp2 && psa->comp2==psb->comp2 && .... )
> #endif
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.