S
Sean Hamilton
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? Since i and j do
not overlap, there should be no pointer aliasing issues, correct? I'm
more concerned about the pointer cast being undefined -- it works with
gcc of course, but I suspect this is not guaranteed.
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 *)? Of course the goal here is to
implement virtual functions. Again it works in gcc, but I'm not sure I
can depend on it.
Getting OT, does gcc make some kind of promise that pointer casts like
this will work, beyond the C standard, or is this some terrible bug
just waiting to emerge? I've noticed this seems pretty widespread in
general, for example the BSD sockets API.
Is there a standard and well-behaved way to do all this, perhaps with
macros? If it's unsafe/undefined, can it be made safe with strategic
casts to (void *)? I've noticed some quick guides to OOP patterns in
C, but they seem to ignore these issues. Should I just use that other
language?
Thanks in advance,
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? Since i and j do
not overlap, there should be no pointer aliasing issues, correct? I'm
more concerned about the pointer cast being undefined -- it works with
gcc of course, but I suspect this is not guaranteed.
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 *)? Of course the goal here is to
implement virtual functions. Again it works in gcc, but I'm not sure I
can depend on it.
Getting OT, does gcc make some kind of promise that pointer casts like
this will work, beyond the C standard, or is this some terrible bug
just waiting to emerge? I've noticed this seems pretty widespread in
general, for example the BSD sockets API.
Is there a standard and well-behaved way to do all this, perhaps with
macros? If it's unsafe/undefined, can it be made safe with strategic
casts to (void *)? I've noticed some quick guides to OOP patterns in
C, but they seem to ignore these issues. Should I just use that other
language?
Thanks in advance,