TAGS :Viewed: 5 - Published at: a few seconds ago

[ Can I use the enum int representation internally? ]

I would like to get rid of most literal values in my code and use enumerations instead. So I created the following enumeration:

enum Axis { X, Y, Z };

Now I want to store data for this and found that I would do this:

vector<T> x, y, z;

And then create a lot of switch statements like this:

switch (axis) {
case Axis::X:
    return x;

Using an int axis, I was able to just do

vector<vector<T>> data(3);

and index it with data[axis] to get the right data set. I thought that I could also use an Axis axis and still to data[axis] using the implicit convertion to int.

Is it a bad thing when I enforce this enumeration most of the time but use the fact that Axis::X == 0 as well? Is that an improvement against using int axis or does it make the whole thing more complicated?

Answer 1

It's totally fine to treat enums as integers, as long as you're clear about what you're doing. Usually, like this:

enum Axis { 
    //axis_count=3, If you intend to iterate over values, add this

This makes it blatantly clear to yourself and other developers that the integer values of each are important, and therefore that the enumerations will sometimes be used as integers.

Vaguely related, it's also common to use enumerations for bitflags, which usually looks more like this:

enum ThingFlags {
    IsTall    = 1<<0,
    IsWide    = 1<<1,
    IsLong    = 1<<2,
    IsHollow  = 1<<3,
    IsColored = 1<<4,

    Mask      = (1<<5)-1, //common to have a mask of all meaningful bits.
    SizeMask  = 0x7,      //sometimes other masks too

And this makes it clear that the least-significant bit signifies height, the next bit is width, the next is length, etc.