C 为什么typedef在nginx中使用如此广泛?
例如,C 为什么typedef在nginx中使用如此广泛?,c,nginx,typedef,C,Nginx,Typedef,例如,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
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;
事实上,我知道可以使用结构名称,例如ngx_module_s
,为什么typedef
将其与ngx_module_t
一起使用?这个设计好吗?这样做有什么好处
在用C语言编程时,这是一种很好的实践吗?那么,这种做法的名称是什么?为什么是好是坏?这是一种常见的做法。您不必每次声明变量时都使用struct关键字。这是一种常见做法。您不必每次声明变量时都使用struct关键字。看看其中一个,定义为:
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;
};
您可以按如下方式使用ngx命令:
struct ngx_command_s *x;
x = malloc(sizeof(struct ngx_command_s));
但是当您使用typedef
时,可以避免使用struct
关键字:
typedef struct ngx_command_s ngx_command_t;
ngx_command_t *x;
x = malloc(sizeof(ngx_command_t));
为什么是好是坏
有些人认为结构的
typedef
是不必要的,而且容易混淆。看看其中一个,定义如下:
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;
};
您可以按如下方式使用ngx命令:
struct ngx_command_s *x;
x = malloc(sizeof(struct ngx_command_s));
但是当您使用typedef
时,可以避免使用struct
关键字:
typedef struct ngx_command_s ngx_command_t;
ngx_command_t *x;
x = malloc(sizeof(ngx_command_t));
为什么是好是坏
有些人认为,结构的Type的TyPufF不必要和混淆,在C中,
< P>,不同于C++,你不能直接用代码来引用<代码>结构> /COD>标签,struct
、union
、enum
,或其他类型)
< P>注意,类型名称的后缀由POSIX保留,因此在技术上,这违反了POSIX标准。< P> C,与C++不同,不能直接用名称来引用<代码>结构> /Calp>TAG,<代码>结构> /代码>必须始终伴随它。这就是使用类型定义的动机,它有时被称为类型别名 一个好处是源代码可以更加清晰,因为冗余信息不会使代码混乱。一个缺点是别名隐藏了它的类型(
struct
、union
、enum
,或其他类型)
请注意,类型名称上的
\t
后缀由POSIX保留,因此从技术上讲,这违反了POSIX标准。您不必在每次创建变量时都使用struct关键字。您可能需要读取。您不必在每次创建变量时都使用struct关键字。您可能需要读取。