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;
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.
enum types are integer types and you are allowed to assign any integer value to any integer object.
This is valid and no diagnostic is required by the Standard. Nevertheless some implementations warn when you try to mix up different enum types.
To silent the warning the best is to not mix up the enum types, but otherwise I would recommend to cast it to the enum type.
b = (EnumB)a;
Except if your compiler is really smart, this:
b = (int)a;
should also work as enum constant are of type int and the compiler is not supposed to warn when the right enum constant (type int) is assigned to the right associated enum type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With