Thursday, March 22, 2012

2 Enums having common values ?

As we mentioned in our previous post, there is this unique problems in enums you may come across sometime that what if 2 enums ended up having some values same, your code will show ERROR, how to solve this ? I will give an example:
Suppose you have an enum

typedef enum
{
        Red ,
        Green,
        Yellow
}BarColors;





typedef enum
{
        Voilet,
        Indigo,
        Blue,
        Green,
        Yellow,
        Orange,
        Red
}RainbowColors;




Now you can see that Red, Green and Yellow are same in both enums. You will get error if you have both enums in your same code. How to deal with it, conventionally you can add a prefix to each enum value like following:

typedef enum
{
        b_Red ,
        b_Green,
        b_Yellow
}BarColors;





typedef enum
{
        r_Voilet,
        r_Indigo,
        r_Blue,
        r_Green,
        r_Yellow,
        r_Orange,
        r_Red
}RainbowColors;


This will solve the error.

No comments:

Post a Comment