Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using a typedef *after* struct definition?

Tags:

c

struct

typedef

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?

like image 271
Gui13 Avatar asked Jul 30 '10 11:07

Gui13


2 Answers

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.

like image 159
Patrick Schlüter Avatar answered Oct 06 '22 00:10

Patrick Schlüter


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).

like image 25
Justin Ethier Avatar answered Oct 05 '22 23:10

Justin Ethier