Casting enum definition to unsigned int

Thomas Matthews picture Thomas Matthews · Jul 3, 2012 · Viewed 43.6k times · Source

According to this SO post:
What is the size of an enum in C?
enum types have signed int type.

I would like to convert an enum definition from signed int to unsigned int.

For example, on my platform an unsigned int is 32-bits wide. I want to create an enum:

typedef enum hardware_register_e
{
    REGISTER_STATUS_BIT = (1U << 31U)
} My_Register_Bits_t;

My compiler is complaining that the above definition is out of range (which it is for a signed int).

How do I declare unsigned int enum values?

Edit 1:

  1. The preference is not to expand to 64 bits (because the code resides in an embedded system).
  2. Due to skill limitations, C++ is not allowed for this project. :-(

Edit 2:

  • Compiler is IAR Embedded Workbench for ARM7.

Answer

ouah picture ouah · Jul 3, 2012

According to this SO post: What is the size of an enum in C? enum types have signed int type.

The thing is enum types can be int type but they are not int in C. On gcc 1), enum types are unsigned int by default.

enum constants are int but enum types are implementation defined.

In your case the enum constant is int but you are giving it a value that does not fit in a int. You cannot have unsigned int enum constants in C as C says they are int.


1) gcc implementation defined enum type documentation: "Normally, the type is unsigned int if there are no negative values in the enumeration, otherwise int" in http://gcc.gnu.org/onlinedocs/gcc/Structures-unions-enumerations-and-bit_002dfields-implementation.html