1

For example there are so many typedefs to a huge number of structures in ngx_core.h

typedef struct ngx_module_s      ngx_module_t;
typedef struct ngx_conf_s        ngx_conf_t;
typedef struct ngx_cycle_s       ngx_cycle_t;
typedef struct ngx_pool_s        ngx_pool_t;
typedef struct ngx_chain_s       ngx_chain_t;
typedef struct ngx_log_s         ngx_log_t;
typedef struct ngx_array_s       ngx_array_t;
typedef struct ngx_open_file_s   ngx_open_file_t;
typedef struct ngx_command_s     ngx_command_t;
typedef struct ngx_file_s        ngx_file_t;
typedef struct ngx_event_s       ngx_event_t;
typedef struct ngx_event_aio_s   ngx_event_aio_t;
typedef struct ngx_connection_s  ngx_connection_t;

In fact, I know the structure name such as ngx_module_s is ok to be used, why typedef it with ngx_module_t? Is this good design? And, what are the benefits to do this?

Is this kind of good practice when programming in the C language? And, what is the name of this practice? Why is it good or bad?

jxh
  • 69,070
  • 8
  • 110
  • 193
hugemeow
  • 7,777
  • 13
  • 50
  • 63

3 Answers3

3

It's a common practice. You don't have use the struct keyword each time you declare a variable.

Charlie Burns
  • 6,994
  • 20
  • 29
3

Look at one of them, is defined as:

struct ngx_command_s {
  ngx_str_t             name;
  ngx_uint_t            type;
  char               *(*set)(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
  ngx_uint_t            conf;
  ngx_uint_t            offset;
  void                 *post;
 };

You can use ngx_command_s as follows:

struct ngx_command_s *x;
x = malloc(sizeof(struct ngx_command_s));

But when you typedef, you can avoid the struct keyword :

typedef struct ngx_command_s ngx_command_t;

ngx_command_t *x;
x = malloc(sizeof(ngx_command_t));

Why is it good or bad?

Some people thinks that typedef for structs are unneccessary and confusing, take a look.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
0

In C, unlike C++, you cannot refer to the struct tag directly by name, the struct must always accompany it. This is the motivation to using the typedef, which is sometimes referred to as type aliasing.

A benefit is that source code can be more clear since redundant information is not cluttering the code. A detriment is that the alias hides the kind of type it is (struct, union, enum, or some other type).

Note that the _t suffix on type names is reserved by POSIX, so technically, this violates the POSIX standard.

jxh
  • 69,070
  • 8
  • 110
  • 193