Both this style:
struct _something
{
...
};
typedef struct _something someting;
and that style:
typedef struct _something
{
...
} something;
are correct typedef declarations in C.
Note that the presence of the structure declaration in the header file is made on purpose: I need to have access to the inner components of the structure somewhere else.
One drawback of the first declaration is that when you use any IDE, the automatic "jump to declaration" often directs you to the typedef struct _something someting;
instead of giving you directly the real structure definition.
In the second method, you get directly to the structure definition.
Is there a reason why one would use the first method?
The code I'm working on is full with these...
Is it simply a bad/good habit from the maintainers?
There's one clear advantage of separating the typedef and the struct declaration and that advantage is clear if you separate both in different files. It allows for data encapsulation.
You declare in the header file your
typedef struct whatever typename;
This is a declaration of a type of struct whatever
without knowing how it is implemented. You can declare now the functions that are part of the interface, without revealing anything from the interna of the structure. Passing a pointer to that typename
is all that is needed.
In the implementation file of your "class" (I put that in quotes as we are talking here purely in a C context), you do this:
#include "header.h"
struct whatever {
...
...
/* can even contain references to `struct whatever` or even `typename` */
};
This encapsulation has the advantage that you can change the internal structure without needing to recompile the rest of the app. Can come handy if you work with dynamic libraries.
This discussion thread gives a good overview of the topic, and highlights an important reason to use the first style:
This style separates type definition (which is not what typedef does) from typename synonym creation (which is what typedef does), and retains a strong correspondence between type name and type synonym without the disadvantage of using the same name for both (which can confuse some debuggers, and in any case is a pain for grep).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With