On 07/08/2013 07:06, stephan beal wrote:
> 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*)⊂
In plain terms, take the memory of sub and treat it as a base. Looks
fine to me because of the prohibition of initial padding in any object.
>
> 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;
Whiist this should work in the current context, it is dangerous as it
relies on the memory addresses by a b* actually containing a subclass
object. Hence I would expect that to be generally classed as undefined
behaviour.
>
> (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.)
You are confusing 'legal' with 'will work as expected'. The
implementation takes the programmer's word that a cast is valid. That is
the nature of casts in C. They are effectively an unchecked way of
changing the type of an area of memory.
>
> 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.
Well C++ makes the same guarantees as C for Plain Old Data types (i.e
structs that conform to the requirements of C) However, the general
rules in C++ have to accommodate inheritance (possibly multiple). As a
result C++ programmers avoid C-style casts because they are blunt tools
in the context of C++.
I guess one of the resident C specialists will quote you chapter and verse.
Francis