On 2010-11-02, Ben Bacarisse <> wrote:
> It's not guaranteed to work, though it is one of those things that
> almost certainly will. The reason is that it *is* guaranteed to work if
> the two structs are members of a union, and the access is through that
> union. For the compiler to arrange the layout of the common initial
> members of the two structs differently it would have to be sure that no
> such access is ever done and it is obviously simpler just to make the
> layout of the common parts be the same "just in case".
The problem isn't layout, it's aliasing.
gcc will, already, generate code which assumes that modifications
through a (struct base *) cannot possibly affect a (struct extended *).
You can easily arrange:
struct base *b = external_base();
struct extended *e = external_extended();
assert(b == e);
e->x = 1;
b->x = 2;
printf("%d\n", e->x);
to print "1". Because the compiler KNOWS that e and b are different objects,
as they're of incompatible types.
-s
--
Copyright 2010, all wrongs reversed. Peter Seebach /
usenet-
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.