With GCC, I could do packing of enums using attribute((packed)), but it seems the closest thing in MSVC, #pragma pack, does not work on enums. Does anyone know of a way to pack enums into 1 byte instead of the usual integer size?
-
given that using it (if it existed) will lead to non portable code, why would you need to use that anyway?– lotharCommented May 7, 2009 at 22:19
-
1Because sometimes portability is irrelevant and compatibility with another system is needed. Years ago I wanted this when communicating via shared RAM to a 68K board (whose compiler supported specifying the size of an enum).– Steve FallowsCommented May 7, 2009 at 22:55
-
@Steve Fallows In that case I would prefer a (set of) functions to convert from the C enum to and from the external format. that is safer (as there may be endian conversions necessary (not in this case, but generally) and portable.– lotharCommented May 7, 2009 at 23:09
Add a comment
|
1 Answer
This is MSVC specific:
// instances of this enum are packed into 1 unsigned char
// warning C4480: nonstandard extension used
enum foo : unsigned char { first, second, last };
assert(sizeof(foo) == sizeof(unsigned char));
// instances of this enum have the common size of 1 int
enum bar { alpha, beta, gamma };
assert(sizeof(bar) == sizeof(int));
For reference see here: MSDN -> enum
-
I think that's C#. I've never seen such syntax in C++. If it works though, that's really cool. I'll refrain from downvoting because I'm unsure.– rmeadorCommented May 7, 2009 at 22:33
-
maybe MSVC already implements c++ 0x, but then it should be "class enum" if I am not mistaken– lotharCommented May 7, 2009 at 22:46
-
2No, it's not C++/CLI or C#. It's a MS extension to plain C++, similar to what gcc does with attribute((packed)).– nusiCommented May 7, 2009 at 22:53
-
1From the link explaining the warning: "An extension to the language under /clr was used without /clr. You can disable C4480". It's a c++/cli extension that you can use in native c++.– EclipseCommented May 7, 2009 at 23:00
-
@rmeador: read the answer -- it is MSVC specific. That means you won't find it in other compilers.– KasprzolCommented May 7, 2009 at 23:03