开发者

Is this a coding convention?

I am doing feature enhancement on a piece of code, and here is what i saw in existing code. If there is a enum or struct declared, later there is always a typedef:

enum _Mode 开发者_如何学Python{
   MODE1 = 0,
   MODE2,
   MODE3
};
typedef enum _Mode Mode;

Similary for structure:

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

Can't the structures be directly declared as in enum? Why there is a typedef for something as minor as underscore? Is this a coding convention?

Kindly give good answers, because i need to add some code, and if this is a rule, i need to follow it.

Please help. P.S: As an additional info, the source code is written in C, and Linux is the platform.


In C, to declare a varaible with a struct type you would have to use the following:

struct _Slot a;

The typedef allows you to make this look somewhat neater by essentially creating an alias. And allowing variable declaration like so:

Slot a;


In C there are separate "namespaces" for struct and typedef. Thus, without a typedef you would have to access Slot as struct _Slot, which is more typing. Compare:

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

Also see http://en.wikipedia.org/wiki/Struct_(C_programming_language)#typedef for details, like possible namespace clash.


If the following is a structure:

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

you need the following to declare a variable:

struct _Slot s;

Notice the extra struct before _Slot. It seems more natural to declare a variable like Slot s, isn't it?

If you want to get rid of extra struct, you need a typedef:

typedef struct _Slot Slot;
Slot s;


It's sort of code obfuscation technique which only make sense in small amount of cases.

People say it's more natural to not write "struct" and other subjective things.

But objectively, one at least a) can't forward declare such typedeffed struct, b) have to jump through one hoop when using ctags.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜