How can I get enum name associated with a int val.
I have following code:
#include<stdio.h>
#include<stdlib.h>
typedef enum _MyID{
id1 = 1,
id2 = 2,
id3 = 3,
}MyID;
MyID get_idname(int id_val)
{
switch(id_val){
case 1:
return id1;
case 2:
return id2;
case 3:
return id3;
default: //checks for invalid ID
return -1;
}
}
int main()
{
int val1 = 1;
int val2 = 2;
MyID new_id1 = (MyID)(val1|val2);
MyID new_id2 = (MyID)(4);
MyID new_id3 = get_idname(3);
MyID new_id4 = get_idname(4);
printf("id is new_id1 %d, new_id2 %d, new_id3 %d, new_id4 %d \n", new_id1, new_id2, new_id3, new_id4);
return 0;
}
The above code outputs the following: id is new_id1 3, new_id2 4, new_id3 3, new_id4 -1
Clearly, typecasting int to enum is dangerous. One way to resolve this is to use a function (like in the above) with switch statement to catch the invalid value passed. The issue with this is, I have really big enum with 100's of values so writing switch case for each enum is hectic task and not scalable approach. I would like to know if there is any efficient solution for the same.