Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> > typedef struct { ... } String

> I avoid doing this. Just use `struct string { ... };'. It makes it clear what you're handling.

Well then imagine if Gtk made you write `struct GtkLabel`, etc. and you saw hundreds of `struct` on the screen taking up space in heavy UI code. Sometimes abstractions are worthwhile.



The main thing I dislike about typedefs is that you can't forward declare them.

If I know for sure I'm never going to need to do that then OK.


How do you mean? You can at least do things like

typedef struct foo foo;

and somewhere else

struct foo { … }


The usual solution for this is:

    typedef struct bla_s { ... } bla_t;
Now you have a struct named 'bla_s' and a type alias 'bla_t'. For the forward declaration you'd use 'bla_s'.

Using the same name also works just fine, since structs and type aliases live in different namespaces:

    typedef struct bla_t { ... } bla_t;
...also before that topic comes up again: the _t postfix is not reserved in the C standard :)


People getting hung up on `_t` usage being reserved for posix need to lighten up. I doubt they'll clash with my definitions and if does happen in the future, I'll change the typedef name.


Yes, using the same Gtk example, the way you’d forward declare GtkLabel without including gtklabel.h in your header would be:

    struct _GtkLabel;
    typedef struct _GtkLabel GtkLabel;
    // Use GtkLabel* in declarations


Why are you complicating things? Struct and Unions are different namespaces for a reason.

    typedef struct GtkLabel GtkLabel;
works just fine.


I’m simply stating how actual Gtk is written:

https://gitlab.gnome.org/GNOME/gtk/-/blob/main/gtk/gtklabel....


True, thanks then. As far as I see it they don't even use the struct in the implementation, so I guess it makes some sense.


> Well then imagine if Gtk made you write `struct GtkLabel`, etc. and you saw hundreds of `struct` on the screen taking up space in heavy UI code. Sometimes abstractions are worthwhile.

TBH, in that case the GtkLabel (and, indeed, the entire widget hierarchy) should be opaque pointers anyway.

If you're not using a struct as an abstraction, then don't typedef it. If you are, then hide the damn fields.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: