8

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;
Aadishri
  • 1,341
  • 2
  • 18
  • 26
  • 1
    Have you tried any of that? – Some programmer dude Feb 06 '15 at 13:05
  • If both have exactly the same value-set, why do you have them both defined at all? Just define one and use that one in both modules. Anyway, casting one enum to another is not always a good idea. It should work though. – rfreytag Feb 06 '15 at 13:08
  • 1
    Which compiler/tool (with what options) causes the warning? There isn't any required by the standard (and `gcc -std=c99 -pedantc -Wall -Wextra` doesn't emit one). – mafso Feb 06 '15 at 13:13
  • I have not tried either. I use gmake – Aadishri Feb 06 '15 at 13:35

2 Answers2

11

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.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
2

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.

ouah
  • 142,963
  • 15
  • 272
  • 331