This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: ISO Aliasing rules question


On Fri, 21 Feb 2003 10:16:02 -0700, law at redhat dot com said:

> struct s1 { double d; };
> struct s2 { double d; };

> double f(struct s1 *a, struct s2 *b)

> int main()
> {
>   struct s1 a;
>   f (&a, (struct s2 *) &a);
> }

(I've chopped the test case.)

I have a few related questions:

1) What if the call to f were changed to

  f (&a, (struct s2 *) &a.d);

or to

    f (&a, (struct s2 *) (double *) &a);

Would that make a difference?

2) What if we have a sequence like this (with the same s1 as above):

void f (struct s1 *s1p);

void g (double *dp)
{
  f ((struct s1 *) dp);
}

void h (void)
{
  struct s1 a;

#ifdef SWITCH
  f (&a);
#else
  g (&p.d);
#endif
}

Does the behavior depend on whether or not SWITCH is defined?


I confess that I don't have a copy of the C standard; I'm just curious
what lies behind the statement in K&R that "If a pointer to a
structure is cast to the type of a pointer to its first member, the
result refers to the first member."

The reason why I ask is that there are places in GDB where we get a
(clumsy) analogue of C++ subclassing by creating a struct whose first
member is another struct (which acts like a superclass).  I think that
everything we do currently in that regard is legit, but I'd like to
augment this by doing a sort of Java-style generic container, where
the container contains a pointer to the first member (the
"superclass") that I'd like to be able to cast back to a pointer to
the entire struct (the "subclass").  I would hope that this is legal
because the K&R quote above suggests that the pointer to the first
member is the same as casting to the superclass, so all I'd be doing
is casting to the superclass and then back to the subclass.  But these
sorts of discussions are making me a bit paranoid about when casts are
ever reliable.

David Carlton
carlton at math dot stanford dot edu


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]