Wednesday, July 14, 2021

C++: Using 1 byte enum

By default, enum size in C++ is usually 4 bytes, both in Windows and Linux. If you need to use 1 byte enum, you have to declare it as follows:

enum e : unsigned char { a, b };

This requires at least C++ 11. printf("size = %ld\n", sizeof(e)) will output 1.

If you are using gcc (e.g. Eclipse), you can also use the compiler flag -fshort-enum (Eclipse properties - C/C++ Build - Settings - Tool Settings - GCC C++ Compiler - Miscellaneous) to convert all enums in code to 1 byte, but you won't have that option in Visual Studio. So it is better to use the unsigned char option.

No comments:

Post a Comment