Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 462
RajSanpui Avatar asked Dec 04 '22 21:12

RajSanpui


2 Answers

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;
like image 190
a'r Avatar answered Dec 08 '22 03:12

a'r


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.

like image 26
vines Avatar answered Dec 08 '22 02:12

vines