James Kuyper
8/18/2011 2:17:00 PM
On 08/18/2011 08:53 AM, Sean Hamilton wrote:
> Hello,
>
> struct super { int i; };
> struct sub { struct super super; int j; };
>
> Is it safe to cast a (struct sub *) to a (struct super *) to access i,
> while using the original (struct sub *) to access j?
Conversion of a pointer to a struct into a pointer to the type of the
first member of that struct is safe and guaranteed to give what you
want. Given:
struct sub *sandwich;
Then you are guaranteed that:
(struct super*)sandwich == &sandwich->super
However, I'd recommend using &sandwich->super. It's not only clearer,
but it will continue to do precisely what needs to be done, even if
someone later decides to insert something before 'super' in struct sub.
> Also what about covariance and contravariance of function pointers
> which accept and return these pointer types? Are these casts
> guaranteed to work? For example, if I have void f (struct super * s),
> can I assign this to a void (*) (struct sub *), and safely call this
> function pointer with a (struct sub *)?
The reverse conversion is also guaranteed to work.
> Getting OT, does gcc make some kind of promise that pointer casts like
> this will work, beyond the C standard,
I've no idea whether gcc guarantees that this works in it's default
mode, where it implements GNU C, not standard C. However, the C standard
does guarantee this, and if you use -ansi, -std=c90 or -std=c99, gcc
will do the same.
--
James Kuyper