这是编码惯例吗?

时间:2011-07-13 08:19:59

标签: c linux coding-style

我正在对一段代码进行功能增强,这就是我在现有代码中看到的内容。如果声明了枚举或结构,则以后总会有一个typedef:

enum _Mode {
   MODE1 = 0,
   MODE2,
   MODE3
};
typedef enum _Mode Mode;

类似于结构:

struct _Slot {
     void * mem1;
     int mem2;
};
typedef struct _Slot Slot;

结构不能直接在枚举中声明吗? 为什么对于像下划线那样轻微的东西有一个typedef?这是编码惯例吗?

请给出好的答案,因为我需要添加一些代码,如果这是一个规则,我需要遵循它。

请帮忙。 P.S:作为附加信息,源代码用C语言编写,Linux就是平台。

4 个答案:

答案 0 :(得分:9)

在C中,要声明具有结构类型的变量,您必须使用以下内容:

struct _Slot a;

typedef允许您通过基本上创建别名使这看起来更整洁。并允许变量声明如下:

Slot a;

答案 1 :(得分:4)

C中, struct typedef 有单独的“命名空间”。因此,如果没有 typedef ,您必须以Slot作为struct _Slot访问,这更像是打字。比较:

struct Slot { ... };

struct Slot s;
struct Slot create_s() { ... }
void use_s(struct Slot s) { ... }

VS

typedef struct _Slot { ... } Slot;

Slot s;
Slot create_s() { ... }
void use_s(Slot s) { ... }

另请参阅http://en.wikipedia.org/wiki/Struct_(C_programming_language)#typedef了解详细信息,例如可能的命名空间冲突。

答案 2 :(得分:2)

如果以下是结构:

struct _Slot {
     void * mem1;
     int mem2;
};

您需要以下内容来声明变量:

struct _Slot s;

请注意struct之前的额外_Slot。声明像Slot s这样的变量似乎更自然,不是吗?

如果您想摆脱额外的struct,则需要typedef

typedef struct _Slot Slot;
Slot s;

答案 3 :(得分:1)

这种代码混淆技术只在少数情况下才有意义。

人们说不写“结构”和其他主观事物更自然。

但客观地说,至少a)不能转发声明这样的typedeffed结构,b)在使用ctags时必须跳过一个环。

相关问题