In article <7f**********************************@8g2000hse.go oglegroups.com>
Kenneth Bull <ke**********@gmail.comwrote:
[given]
>struct foo
{
int x;
double y;
/* etc. more variables defined */
short u;
char z;
} a;
Are the following true on all systems?
1) &a == &a.x
"Sort of". The problem here is that &a and &a.x have different
*types*. This is a bit like asking whether 3 and 3.0 are "the
same":
#include <stdio.h>
int main(void) {
if (3 == 3.0) puts("3 and 3.0 are identical");
if (sizeof 3 != sizeof 3.0) puts("3 and 3.0 are different");
return 0;
}
This program, run on most of my machines, says that 3 and 3.0 are
both identical *and* different (because they compare equal, but
"sizeof 3" is 4, and "sizeof 3.0" is 8).
If you convert &a and &a.x to some common (and thus comparable)
type, they will be equal, provided of course the conversion is
valid in the first place. For instance:
assert ((void *)&a == (void *)&a.x);
will never fail.
(Contrast this with, for instance:
if ((char)3 == (char)3.1415) puts("3 and 3.1415 are identical");
which claims that they are identical. After converting to one
common type, they are equal, but if we chose a different type --
such as "float" or "double" -- they would compare unequal. The
Standard says that, for the first element of the "struct", we can
choose *any* suitable type -- such as "struct foo *" or "void *"
-- and the results of the conversion will compare equal.)
>2) (&a.x < &a.y) && ( .. etc.. ) && ( &a.u < & a.z)
Again, these have type mismatches. If we convert them to suitable
comparable types, though, this does in fact hold in Standard C.
(It does not hold in some extended versions of C, including GNUC,
where a "zero sized array" may occupy no space.)
>Are the following true if we change 'struct' to union above, on all
systems?
3) &a == &a.x
4) &a.? == &a.? where ?s can be x, y, ..., u, or z (not necessarily
equal for both ?s)
Yet again, we have the type mismatch problem, but if we convert all
the addresses to either "void *" or "union foo *", they will indeed
all compare equal.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: gmail (figure it out)
http://web.torek.net/torek/index.html