When should one of the following statements be used over the other?
typedef struct Foo {
int a;
} Bar;
and
typedef stru
It doesn't really matter much. If you use the tagged form you can
have pointers to struct Foo
inside struct Foo
(AKA Bar)
typedef struct Foo{
int a;
struct Foo *foop;
} Bar;
but there's no way to do that with the second form
typedef struct {
int a;
//Baz *p; not valid here since Baz isn't a typename yet
} Baz;
Some codebases prefer not to use typedef
s at all and simply spell out struct Foo
with the struct keyword every time.
Also, with the first form, you can refer to the type either via the tag (struct Foo
) or with typedefs
(Bar
or any future/previous typedef
s (you can do typedef struct Foo PreviousTypedef;
before you provide the definition).
With the second form, on the other hand, you can only use the Baz
typedef
and possible future typedef
s (you can't forward-typedef
the struct since it doesn't have a tag).
(Note that typedef
doesn't really define types in C. The struct optional_tag { /*...*/ }
part does. Rather, typedef
provides type aliases (so perhaps it should have been named typealias
).)