0

We know that C store enum types internally as int, which means that the size of the enum is 4 bytes in 32/64 bit machine.

But considering int is signed and range from −2,147,483,648 to 2,147,483,647, we certainly don't need that many available values. We can use unsigned short (max 65,535) or even unsigned char (max 255) suffices. So my questions are:

Q1-why C don't make enum type store unsigned short/char internally?

Q2-Why we need to use typedef to declare an enum e.g

typedef enum { N_LEAF, N_INTERNAL } nodetype_t;

but we don't need to use typedef in struct declaration e.g

struct node_s {
   char c;
   int i[2];
};

Why we can't make enum declaration the same as struct as:

enum { N_LEAF, N_INTERNAL } nodetype_t;

1 Answers1

0

We cannot say beforehand if sizeof(int) is too big for enum, as some may want it to be as large as that. Anyway, check: Here which mentions:

Normally, the type is unsigned int if there are no negative values in the enumeration, otherwise int. If -fshort-enums is specified, then if there are negative values it is the first of signed char, short and int that can represent all the values, otherwise it is the first of unsigned char, unsigned short and unsigned int that can represent all the values. On some targets, -fshort-enums is the default; this is determined by the ABI.

You do not need to use typedef with enum. The use of typedef is the exact same in struct and enum. Try to create an enum with and without typedef.

Ajay Nair
  • 23
  • 5