I’m making a enum in c++ to make a finite state machine using binary flags. It looks like:
enum VStates
{
NEUTRAL = 0x00000000, // 000000
// Physical Status
DRY = 0x00000001, // 000001
WET = 0x00000002, // 000010
HOT = 0x00000004, // 000100
COLD = 0x00000008, // 001000
BURNED = 0x00000016, // etc..
FROZEN = 0x00000032,
EROS = 0x00000064, //
THANATOS = 0x00000128, //
SLEEP = 0x00000256,
STUNNED = 0x00000512,
PARALYZED = 0x00001024,
POISONED = 0x00002048, //
BLIND = 0x00004096,
SOFT = 0x00008192, // Flexible
TOUGH = 0x00016384, // Resistent
MAGNETIZED = 0x00032768,
POSSEDERUNT = 0x00131072, //
// Mental Status
ANGRY = 0x00262144,
DRUGGED = 0x00524288, // Drugs Meaning
HORNY = 0x01048576, // Sexual Meaning
// Material Status
METAL = 0x02097152,
WOOD = 0x04194304,
GLASS = 0x08388608,
AIR = 0x16777216,
EARTH = 0x33554432,
DUST = 0x67108864,
LIGHT = 0x134217728,
SHADOW = 0x268435456,
WATER = 0x536870912,
// Total Status
PROTECTED = 0x1073741824,
INVULNERABLE = 0x2147483648
};
Some status are incompatibles, so I use Bitwise operators to manage them. Now, my compiler say:
warning: integer constant is too large for 'long' type
Is this the correct way to declare this enum? I like avoid warning so, How can I resolve this problem?
(Note: to make my answer complete I’ll add in something I didn’t take time to notice but others have pointed out: you’re using the
0xprefix, which means your numbers would be interpreted as hexadecimal. They’d not actually be powers of two, and your bitflag tests would not have worked!)If your enumerations are running out of control like this, don’t use an enumerated type. Use something like a
std::bitset. Then your enum can just be a simple numbered list of names for the positions of the bits in the set…and you won’t be exhausting your enumeration space exponentially!For example:
Now your enum is just small, maintainable numbers and you don’t have to worry about being on a 64-bit platform or whatnot.
I note that you gave a value of “0” for NEUTRAL in your original example. If your intent was to have it be possible to use this in combination with other things…such as being able to be
state = NEUTRAL | INVULNERABLE | SHADOWand individually test forNEUTRAL, that wouldn’t have worked before. It will now…you’d just keep it in the enumeration for indexing the bitset.But if it intended as a name for “nothing set”, then you would remove it from the enum and instead test for no bits set with:
…and if you wanted to set all the bits to false, you’d go with: