Using an enum as an array index

前端 未结 7 1446
忘了有多久
忘了有多久 2020-12-13 12:30

I have this enum:

enum ButtonState {
    BUTTON_NORMAL = 0,
    BUTTON_PRESSED = 1,
    BUTTON_CLICKED = 2
};

const u8 NUM_BUTTON_STATES = 3;
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 12:56

    Is this good programming style?

    I think so. I do the same thing quite frequently.

    Is there a better way to do it?

    class Button
    {
    public:
        // Used for array indexes!  Don't change the numbers!
      enum State {
        NORMAL = 0,
        PRESSED,
        CLICKED,
        NUMBER_OF_BUTTON_STATES
      };
    };
    

    Drawback is that NUMBER_OF_BUTTON_STATES is now a valid Button::State value. Not a big issue if you are passing these values around as ints. But trouble if you are actually expecting a Button::State.

    Using an enum as an array index doesn't feel right.

    It's fine. Just DOCUMENT it, so the next guy knows what's going on! (That's what comments are for.)

    Do I have to specify the values of the enum?

    With no '=' assignment, enum's are supposed to start at zero and increment upwards.

    If a enum entry has an '=' assigned value, subsequent non '=' enum entries continue counting from there.

    Source: The Annotated C++ Reference Manual, pg 113

    That said, I like to specify the initial value just to make the code that much clearer.

提交回复
热议问题