Re: Typedef structs

From: Tim Rentsch (txr_at_alumnus.caltech.edu)
Date: 08/31/04


Date: 30 Aug 2004 20:44:18 -0700

Keith Thompson <kst-u@mib.org> writes:

> Tim Rentsch <txr@alumnus.caltech.edu> writes:
> [...]
> > Right from the very beginning, C programmers should be taught
> > to follow the pattern
> >
> >
> > typedef struct some_type_name_struct_tag some_type_name;
> >
> >
> > struct some_type_name_struct_tag {
> >
> > /* ... definition goes here ... */
> >
> > };
> >
> >
> > and elsewhere always use 'some_type_name' to refer to the structure
> > type.
>
> The counterargument is that it hides (or attempts to hide) information
> that shouldn't be hidden.
       ^^^^^^^^^
What reasons would you offer that it shouldn't be hidden? In a separate
article I responded to another poster's query and listed some advantages
of the separate type name approach. Could one of the just-use-structs
advocates respond and list some principal advantages of not using
a separate type name?

> Assigning a simple name to a complicated type can be useful if the
> goal is data abstraction.

More importantly, information hiding. See the well-known papers
by David Parnas. Also Brooks's "Mythical Man Month", 20th Anniversary
Edition.

> For a struct type, however, there's often not much you can do with the
> type without knowing that it's a struct. [...]

Here's a list of things that can be done with (most) complete types,
without knowing what type they are:

    1. Declare variables of the type (and arrays-of and pointers-to same)
    2. Assign values (and accept parameters and return results)
    3. Pass values to functions, and get values back as results
    4. Take the address with '&'
    5. Use 'sizeof' to get the size, which allows allocation with 'malloc()'

In C99 that might be all complete object types - I'm unsure about the status
in C99 of array assignment. Note that the list is more than enough to allow
useful work to get done, as the 'FILE' example demonstrates.

> A good rule of thumb is probably:
>
> [...]

Let me suggest this rule: Always use typedefs for structs, except in
cases where the advantages of not using them outweigh the advantages
of using them. I've yet to see a statement in this thread about what
the advantages of not using typedefs for structs are, let alone a
comparison of the different advantages for the two approaches.

> (Personally, I'm not as opposed to gratuitous typedefs for structs as
> some people are, but I understand the arguments.)

Keith, I'm disappointed. This kind of rhetoric - a content-free
statement giving a "non-argument" argument, including the emotional
hook word "gratuitous" - should be below you.