Re^2: struct comparison
Maarten Litmaath
maart at cs.vu.nl
Sat Jul 15 10:30:41 AEST 1989
henry at utzoo.uucp (Henry Spencer) writes:
\In article <2874 at solo3.cs.vu.nl> maart at cs.vu.nl (Maarten Litmaath) writes:
\>Why does the PROGRAMMER have to go through all that trouble?
\>I just want to say:
\>
\> puts(mork == mindy ? "equal" : "unequal");
\>
\>Is the ANSI committee trying to tell us the compiler cannot transform the
\>equality test into the correct member-by-member comparison code?
\
\Yes. Think about unions. Or pointers (do you compare the pointers or
\what they point at?). The compiler just doesn't have enough information.
I thought of those as well:
1) pointers - They should be compared themselves; if they don't point to
the same location, they're unequal by definition; if the data they
point at are equal, that's mere coincidence.
2) unions - Compare with the following example:
struct foo {
char bar[10];
} x, y;
(void) strcpy(x.bar, "123456789");
(void) strcpy(y.bar, "987654321");
(void) strcpy(x.bar, "zork");
(void) strcpy(y.bar, "zork");
puts(x == y ? "yes" : "no");
I say the output should be "no", because all 10 bytes in `bar' must
be compared. (The array needn't be a string at all! I might have used
it to store small integers.)
If you want to get "yes", you have to make sure there's no garbage
at the end of `bar', i.e. you must clear the unused part explicitly.
Unions can be dealt with likewise.
I KNOW these two specifications might cause some surprises in actual code,
but:
1) Compare with this little gem to confuse Pascal programmers:
if ("string" != "string")
puts("how weird!");
2) The following example shows how useful struct comparison could be:
struct complex {
int real;
int imag;
} z, w;
...
if (z == w) ...
--
"... a lap-top Cray-2 with builtin |Maarten Litmaath @ VU Amsterdam:
cold fusion power supply" (Colin Dente) |maart at cs.vu.nl, mcvax!botter!maart
More information about the Comp.std.c
mailing list