Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define enum type in C

Tags:

c

enums

typedef

How can I define the type of an enum to be uint8 instead of int?

typedef enum
{
  R_DIRECTION_LEFT = 1,
  R_DIRECTION_RIGHT = 2,
  R_DIRECTION_TOP = 4,
  R_DIRECTION_BOTTOM = 8
} R_Direction;
like image 518
Ronen333 Avatar asked Oct 24 '25 16:10

Ronen333


2 Answers

No you can't.

From standard §6.4.4.3 C11 standard N1570

An identifier declared as an enumeration constant has type int.

like image 182
user2736738 Avatar answered Oct 26 '25 08:10

user2736738


The identifiers in an enum list have type int, as per §6.7.2.2 3 of the C11 Standard:

The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted.

But, enumerations constitute distinct types §6.2.5 16:

Each distinct enumeration constitutes a different enumerated type.

Of the enumerated type itself, the Standard says in §6.7.2.2 4 only that:

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

Further, in a footnote it is pointed out that:

An implementation may delay the choice of which integer type until all enumeration constants have been seen.

So the type of an enumeration is distinct, and this type must be compatible with one of char, a signed integer type, or an unsigned integer type. Which of these will be used is implementation-defined, and may vary from case to case on the same implementation.

like image 23
ad absurdum Avatar answered Oct 26 '25 07:10

ad absurdum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!