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:
September 2nd, 2010 at 1:42 am
Out of curiosity, apart from when coding 4k or 64k; when is it that important to save those few bytes?
September 2nd, 2010 at 2:12 am
It is supported by gcc, just use the -std=c++0x flag
September 2nd, 2010 at 4:05 am
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
September 2nd, 2010 at 4:07 am
And btw, IT IS supported by GCC starting from 4.4:
http://gcc.gnu.org/projects/cxx0x.html
September 2nd, 2010 at 5:55 am
It’s important on PS3 for example, where the SPU memory is quite limited. Thanks for your feedback guys, very useful.
September 9th, 2010 at 5:54 am
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