8 bit enum, in C

Viewed 15175

I have to store instructions, commands that I will be receiving via serial. The commands will be 8 bits long.

I need to preserve transparency between command name, and its value. So as to avoid having to translate an 8-bit number received in serial into any type.

I'd like to use Enumerations to deal with them in my code. Only a enumeration corresponds to a on this platform a 16 bit integer.

The platform is AVR ATmega169V microcontroller, on the Butterfly demo board. It is a 8bit system with some limited support for 16bit operations. It is not a fast system and has about 1KB of RAM. It doesn't have any luxuries like file I/O, or an operating systems.

So any suggestions as to what type I should be using to store 8-bit commands?
There has got to be something better than a massive header of #defines.

6 Answers

You are trying to solve a problem that does not exist.

Your question is tagged C. In C language enum types in value context are fully compatible with integral types and behave just like other integral types. When used in expressions, they are subjected to exactly the same integral promotions as other integral types. Once you take that into account, you should realize that if you want to store values described by enumeration constants in a 8-bit integral type, all you have to do is to choose a suitable generic 8-bit integral type (say int8_t) and use it instead of enum type. You'll lose absolutely nothing by storing your enum constant values in an object of type int8_t (as opposed to an object explicitly declared with enum type).

The issue you describe would exist in C++, where enum types are separated much farther from other integral types. In C++ using an integral type in place of enum type for the purpose of saving memory is more difficult (although possible). But not in C, where it requires no additional effort whatsoever.

Related