Groups | Search | Server Info | Login | Register
Groups > comp.lang.c.moderated > #456
| From | stephan beal <sgbeal@googlemail.com> |
|---|---|
| Newsgroups | comp.lang.c.moderated |
| Subject | Casting the first member of a struct (and back) |
| Date | 2013-08-07 01:06 -0500 |
| Organization | Usenet Fact Police |
| Message-ID | <clcm-20130807-0001@plethora.net> (permalink) |
Hi, Gurus,
i'm trying to clarify my understanding of how exactly the casting rules work for the first member of a C struct. For example...
struct Base {
int foo;
...
};
struct Subclass {
Base base;
...
};
(struct typedefs elided)
Subclass sub = { {...}, ... };
Base * b = (Base*)⊂
It is my understanding (please correct me if i'm wrong) that that is completely kosher in C because C guarantees (IIUC) that the offset of the first member in the struct is 0.
What i'm not clear on is if the reverse of that cast is legal:
Subclass * original = (Subclass*)b;
(insofar as the coder knows that the conversion is legal, of course, e.g. by checking a type-id indicator stored in the base type.)
My intuition says, "if the offset is 0, the reverse cast must be just as legal because the address is the same," but i am experienced enough to know that intuition is only a part of the story when it comes to details like this :/. Additionally, i seem to remember reading that C++ does _not_ guaranty that the addresses are the same for such casts.
Can one of you provide me a bit of enlightenment on this topic?
:-?
--
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.
Back to comp.lang.c.moderated | Previous | Next — Next in thread | Find similar
Casting the first member of a struct (and back) stephan beal <sgbeal@googlemail.com> - 2013-08-07 01:06 -0500
Re: Casting the first member of a struct (and back) Francis Glassborow <francis.glassborow@btinternet.com> - 2013-08-07 13:51 -0500
Re: Casting the first member of a struct (and back) Keith Thompson <kst-u@mib.org> - 2013-09-02 04:07 -0500
Re: Casting the first member of a struct (and back) James Kuyper <jameskuyper@verizon.net> - 2013-08-07 13:51 -0500
Re: Casting the first member of a struct (and back) Jasen Betts <jasen@xnet.co.nz> - 2013-08-07 13:51 -0500
csiph-web