How to cast / assign one enum value to another enum

cenums

I have 2 enums in 2 different modules that have exactly same value-set. How can I cast one to another?

typedef EnumA{
a_dog = 0,
a_cat = 1
} EnumA;

typedef EnumB{
b_dog = 0,
b_cat = 1
} EnumB;

EnumA a = a_dog;
EnumB b;

b = a;

Such an assignment is resulting in a warning: enumerated type mixed with another type
Can I avoid switch-case by typecasting, like say

b = (int)a;

or

b = (EnumB)a;

Best Answer

I made a working code from your question. You have missed the enum from your type definitions.

typedef enum EnumA
{
    a_dog = 0,
    a_cat = 1
} EnumA;

typedef enum EnumB
{
    b_dog = 0,
    b_cat = 1
} EnumB;

int main()
{
    EnumA a = a_dog;
    EnumB b;

    b = (EnumB) a;
    printf("%d\n", b);
    return 0;
}

The code b = a also works properly without the cast. Also b = (int) a; is working - at least in C11, becuse enums are really just integers. Anyway, IMHO it is good practice to make an explicite cast.