Re: struct syntax



There is of course a thrid possible syntax...

    struct Thing {
       /* stuff */
      };

This is preferred for code that is used in C++ with forward
declrations being done like

    struct Thing;

As I recall, this works in plain C too, at least with a recient gcc.
In C++, typedefs work but are considered "evil".  They don't
really provide any type-safety.

>
>
> Federico Mena Quintero <federico ximian com> writes:
>
> > On 01 Jul 2001 11:32:50 -0400, Nathan Cullen wrote:
> > >
> > > In Gtk+/GNOME programming I often see:
> > >
> > > /* Style 1 */
> > > typedef struct _Thing Thing;
> > > struct _Thing {
> > > /* stuff */
> > > };
> > >
> > > I also see:
> > >
> > > /* Style 2 */
> > > typedef struct {
> > > /* stuff */
> > > } Thing;
> > >
> > >
> > > It seems as if Style 2 is alot clearer, and gets rid of an unnecessary
> > > middleman.
> > >
> > > The only application of Style 1 that I can concieve of is so that you
> > > could hide implementation details from clients by placing the typedef
in
> > > the header and defining the struct in the corresponding .c file.
> > > clients.  I saw this used effectively in bonobo-ui-node.
> > >
> > > So why do I see Style 1 all over the place?  There must be something
I'm
> > > missing.
> > Historical reasons; the original GTK+ had Style 1 all over the place and
> > it stuck.
> >
> > Style 1 is of course ugly and evil, and all Right Minded people should
> > use Style 2 :)
>
> You frequently want forward declarations because:
>
>  A) Your structures are opaque to user code [ a "good thing" ]
>
>  B) Your structures reference each other recursively, or
>     reference themselves.
>
>  C) You simply don't want to have to worry about ordering.
>
> So, we've always found it easier and more logical to _always_
> forward declare, rather than forward declare a random
> subset.
>
> If you consistently name the structure and the typedef,
> then it doesn't make it any harder to read the code ...
> you always know that the structure for GtkFoo is called
> struct _GtkFoo.
>
> (People frequently point out that the underscore is unnecessary
> and technically invalid. We know that, we aren't going
> to change at this point, and if a C library calls things
> _Gtk... then we'll suffer the conquences.)
>
> Many "utility" structures used right at the point of
> declaration within a single C file are, however, done
> without the forward declaration.
>
> Regards,
>                                         Owen
>
> _______________________________________________
> gnome-devel-list mailing list
> gnome-devel-list gnome org
> http://mail.gnome.org/mailman/listinfo/gnome-devel-list
>






[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]