Edit: Regarding closing the question for being opinion based. I am specifically fishing for anything that is strictly objective and not subjectivity. If there is no objective difference then the answer that states so gets the checkmark. There seems to be definitive objective differences though.
Regarding the how and why to use typedef in C is contained in numerous questions here on SO, but none seem to describe which usecase should be used, or the pro/cons for each.
Most questions regarding the subject revolves around this
struct Bar {
int value;
};
struct Foo {
int value;
};
typedef struct Foo Foo;
struct Bar mybar; // Have to add keyword struct for it to work
Foo myfoo; // Works without struct keyword
My question is more what is the best practice or what should one avoid for which reasons? Could there be issues with using any of the examples below? Or in case of different answers due to context, what are the pro/cons of the given examples
// 1
typedef struct {
int value;
} Foo;
// 2
typedef struct Foo {
int value;
} Foo;
// 3
typedef struct Foo_s {
int value;
} Foo_t;
// 4
typedef struct Foo {
int value;
} Foo_t;
Should any of these be avoided, and why? If any of these is not as good, are the same exact points valid for enums? I feel that the whole subject is a bit vague and I havent atleast found anything clear on the issue, so I'm just double checking so that nothing comes back to bite me later.
If there are other variations I can add them.
In a typedef declaration similar to this
// 1
typedef struct {
int value;
} Foo;
you can not refer to the structure within the structure definition. So for example you can not declare a structure that denotes a node of a linked list because within the structure you need to refer to a pointer to the structure type that points to the next node.
In this typedef definition
// 3
typedef struct Foo_s {
int value;
} Foo_t;
two different names Foo_s
and Foo_t
only confuse readers of code. For example it can be written like
struct Foo_s f = malloc( sizeof( Foo_t ) );
or
Foo_t f = malloc( sizeof( struct Foo_s ) );
This typedef definition
// 4
typedef struct Foo {
int value;
} Foo_t;
has the same problem. For example if you will encounter two declarations like this
struct Foo f1;
and
Foo_t f2;
it is difficult to say whether the both types are the same.
So I prefer the following typedef definition
// 2
typedef struct Foo {
int value;
} Foo;
Now you know that the identifier Foo
is reserved for the structure.