Controlling the size of enums

The size of enums is compiler-dependent, and usually you don’t have any control over it. For example let’s have this simple enum for some types:

Then let’s check the size of the enum type:

With MSVC 2008, s = 4. This is clearly a waste of space in this case, since the type could be safely encoded on a single byte. So how do you tell the compiler about this? Well it turns out MSVC allows this nice syntax to control the size of the enum:

And that’s it! Compile with this, and s = 1. This is very useful when trying to save some bytes in a class while retaining the type safety provided by the enum. I think this notation is part of C++0x and will be supported in all compilers at some point. Right now though, it doesn’t seem to work with GCC.

For a portable solution, one probably needs to use templates, maybe something like:

…you get the idea.

6 Responses to “Controlling the size of enums”



  1. guardian Says:

    Out of curiosity, apart from when coding 4k or 64k; when is it that important to save those few bytes?

  2. David Sveningsson Says:

    It is supported by gcc, just use the -std=c++0x flag

  3. SoulTaker Says:

    This is good one, but isn’t is part of c++0x?
    And if not, maybe you should mention this one:
    http://en.wikipedia.org/wiki/C%2B%2B0x#Strongly_typed_enumerations

  4. SoulTaker Says:

    And btw, IT IS supported by GCC starting from 4.4:
    http://gcc.gnu.org/projects/cxx0x.html

  5. admin Says:

    It’s important on PS3 for example, where the SPU memory is quite limited. Thanks for your feedback guys, very useful.

  6. Jonathan Says:

    You can use the packed attribute with gcc to minimise the size of an enum - see, for example, http://codingrelic.geekhold.com/2008/10/ode-to-enum.html

shopfr.org cialis