structure and array and string comparisons

rcd at opus.UUCP rcd at opus.UUCP
Wed Mar 21 14:43:50 AEST 1984


<>
> Personally I think that avoiding structure comparison "because it's hard"
> is a copout.  It's already "hard" for the C programmer who has to compare
> each member of the structure individually.  For the compiler, 99% of the
> cases are without holes and it's easy and efficient.
>
> I don't propose comparing unions, or following pointers.

I'm sorry I ever slipped and understated the situation!  When I said that
comparing structures is "hard" I meant that it's hard enough to be
impractical.  Unions are perhaps the worst aspect, and you CAN'T avoid
unions if you are going to compare structures, because a structure can
contain a union.  Filling in a little bit of the reasoning:  The elements
of a union can be of differing size.  If you compare two instances of a
struct-containing-union, you have to know how much of the union to compare,
to avoid a spurious mismatch on the unused trailing part of a short field.
To do that, you have to know which field of the union is the current one,
which in turn would mean that code would be required at EVERY assignment to
a field of the union (plus or minus some very messy optimization) to keep
track of the current field.  This isn't even remotely practical with C's
undiscriminated union.

[OK, at least 5% of you are ready to suggest allowing "comparisons of
structures unless they contain unions".  Please don't.  First, this is
pretty clearly a clunky special case we don't need - but it also makes a
mess of a certain sort of data-hiding:
	struct junk {
		int a,b,c,d;
		mystery xyzzy;
	}
where "mystery" is a typedef from elsewhere.  The "junk" type shouldn't
have to care what's in type "mystery"; it just needs one.  (Data
abstraction and all that apple pie...)  However, the semantics of objects
of type "struct junk" - in particular, whether they can be compared - would
depend on whether "mystery" was, or contained, a union.]
-- 
{hao,ucbvax,allegra}!nbires!rcd



More information about the Comp.lang.c mailing list