2

I was wondering if it is possible to have an array value in an enum? Example

    enum RGB {
      RED[3],
      BLUE[3]

    } color;

That way RED could contain values of (255,0,0) since that is the RGB color code for red.

2
  • 1
    Enums aren't really meant to contain values. you could have a static const int enumValues[numColors][3] containing colors corresponding to enums. You still can do enum RGB { RED = 0xff000, BLUE=0x00ff00, ...}. Commented Jun 9, 2016 at 15:06
  • yeah I know in worst case scenario I would just use that instead. Thanks for the help Commented Jun 9, 2016 at 15:09

4 Answers 4

3

You cannot do that. The tokens in an enum can only hold integral values.

A possible solution:

struct Color {uint8_t r; uint8_t g; uint8_t b;}; 

Color const RED = {255, 0, 0};
Color const GREEN = {0, 255, 0};
Color const BLUE = {0, 0, 255};
Sign up to request clarification or add additional context in comments.

Comments

3

No you can't do that with an enum. It looks a lot like you want a class/struct:

class Color {
public:
    int red;
    int green;
    int blue;

    Color(int r, int g, int b) : red(r), green(g), blue(b) { }
};

Once you have that class defined, you can then put it into a container (e.g. array, vector) and look them up. You could use an enum to refer to elements in an array, for example.

enum PresetColor {
    PRESET_COLOR_RED,
    PRESET_COLOR_GREEN,
    PRESET_COLOR_BLUE,
};

...
Color presetColors[] = { Color(255, 0, 0), Color(0, 255, 0), Color(0, 0, 255) };

Color favouriteColor = presetColors[PRESET_COLOR_GREEN];

With that in mind, you could wrap all this up to be more maintainable, but I would say that's out of the scope of this question.

Comments

1

To make a long story short: NO, it is not possible.

Comments

0

No, the definition of enums only allows for them to hold integer values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.