On 11/5/2010 10:34 PM, Jon wrote:
> [...]
> If the structs *were* declared the same though, there certainly would be
> no issue whatsoever, right? As in:
>
> struct X {
> int x;
> char y;
> double z;
> };
>
> struct Y{
> int x;
> char y;
> double z;
> };
>
> void X_func(struct X *x);
>
> struct Y y;
> X_func((struct X*)&y);
The fact that you need a cast to avoid a diagnostic should be
a tip-off that something's wrong. The two structs *probably* have
identical layout, that is,
offsetof(struct X, x) == offsetof(struct Y, x) // both 0
offsetof(struct X, y) == offsetof(struct Y, y)
offsetof(struct X, z) == offsetof(struct Y, z)
.... will probably all be true. The Standard doesn't guarantee it,
but any sane compiler will behave this way. Nonetheless, the two
struct types are not "compatible," as the Standard defines the word.
As various people have pointed out, identical representation is
*not* enough to make everything hunky-dory. Suppose your X_func()
uses a `struct Y*' internally, one it gets from a global variable,
perhaps. Since it "knows" that its `struct X*' parameter cannot point
at a `struct Y', it "knows" that accesses via the parameter and via
the internal pointer cannot interfere: Storing through one of them
cannot alter what's pointed at by the other. Of course, all this
"knowledge" rests upon a falsehood, because you've used a cast to
point the parameter at a `struct Y' after all. And if that `struct Y'
happens to be the one the internal pointer also points at ... You've
lied to the compiler, and must expect it to get its revenge.
Why are you so interested in contriving ways to shoot yourself in
the foot? Is there an actual problem you're trying to solve, or are
you just indulging a morbid curiosity?
--
Eric Sosman
lid