Is this a coding convention?

I am making a feature enhancement on a piece of code, and this is what I saw in the existing code. If there is an enumeration or declared structure, there is always a typedef later:

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

Simulation for structure:

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

Is it not possible to directly declare structures in enum? Why is there a typedef for something less like underscore? Is this a coding convention?

Please give good answers, because I need to add code, and if this is the rule, I must follow it.

Please, help. PS: For additional information, the source code is written in C, and Linux is a platform.

+4
source share
4 answers

In C, to declare varaible with a structure type, you will need to use the following:

 struct _Slot a; 

typedef allows you to make this look a little more neat, essentially creating an alias. And allow the declaration of the variable as follows:

 Slot a; 
+9
source

In C there are separate “namespaces” for struct and typedef . Thus, without a typedef, you will need to access Slot as a struct _Slot , which is more typed. For comparison:

 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, such as a possible namespace conflict.

+4
source

If the following structure:

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

To declare a variable, the following is required:

 struct _Slot s; 

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

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

 typedef struct _Slot Slot; Slot s; 
+2
source

This is a kind of code obfuscation method that only makes sense in a small number of cases.

People say that it’s more natural not to write “structure” and other subjective things.

But objectively, at least a) cannot forward the declaration of such a typed structure, b) you have to jump through one hoop when using ctags.

+1
source

All Articles