1

I am creating a large scale simulation with many parts , I am using an enum to distinguish between the multiple parts. I would like to know what the memory cost of using an enum is ,as I want to keep the space taken up by the part to a minimum .

Is it better to use uint8_t instead of an enum ?

7
  • 2
    Typical C compilers allocate the smallest integer size. You can always check sizeof( myenum ) ... Commented Jun 23, 2016 at 18:14
  • 3
    You can specify the integer type of the enum (enum foo : uint8_t {}) Commented Jun 23, 2016 at 18:15
  • Reminder: enum is a signed integer by default. Commented Jun 23, 2016 at 18:17
  • @lorro Is it the same in cpp too ? Commented Jun 23, 2016 at 18:18
  • 1
    The default size of an enum is the smallest signed int that can contain the values. Commented Jun 23, 2016 at 18:52

1 Answer 1

6

In C++ (any version), the underlying type of an enumeration is int by default, unless every enumerator value cannot be represented as an int. In this case, an implementation-defined type is used (one large enough to represent every enumerator value). Note that the size of int depends on your machine. It might be 16 bits, but is probably 32 bits (even on 64-bit machines). Ultimately, it is decided by the compiler.

Since C++11, you can specify the underlying type when declaring the enumeration, using the following form :

enum name : underlying_type { ... }; // For example enum MySmallEnum : char { ... }; 

Source : cppreference.com

In C, it seems like it obeys the same rule as in C++ (before C++11).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.