1

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?

3
  • given that using it (if it existed) will lead to non portable code, why would you need to use that anyway?
    – lothar
    Commented May 7, 2009 at 22:19
  • 1
    Because 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). Commented 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.
    – lothar
    Commented May 7, 2009 at 23:09

1 Answer 1

3

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

5
  • 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.
    – rmeador
    Commented May 7, 2009 at 22:33
  • maybe MSVC already implements c++ 0x, but then it should be "class enum" if I am not mistaken
    – lothar
    Commented May 7, 2009 at 22:46
  • 2
    No, it's not C++/CLI or C#. It's a MS extension to plain C++, similar to what gcc does with attribute((packed)).
    – nusi
    Commented May 7, 2009 at 22:53
  • 1
    From 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++.
    – Eclipse
    Commented May 7, 2009 at 23:00
  • @rmeador: read the answer -- it is MSVC specific. That means you won't find it in other compilers.
    – Kasprzol
    Commented May 7, 2009 at 23:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.