Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast / assign one enum value to another enum

Tags:

c

enums

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;
like image 616
Aadishri Avatar asked Feb 06 '15 13:02

Aadishri


2 Answers

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.

like image 81
meskobalazs Avatar answered Oct 12 '22 04:10

meskobalazs


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.

like image 20
ouah Avatar answered Oct 12 '22 05:10

ouah