nicolas
nicolas

Reputation: 9805

implicit type conversion for enum type in C

In C, is there a way to declare an implicit type conversion for the following union type:

enum COMP { 
  LessThan, 
  Equal, 
  GreaterThan 
};

mapping it to, say, an integer:

enum COMP { 
  LessThan : 1, 
  Equal : 0, 
  GreaterThan : -1 
};

Upvotes: 0

Views: 523

Answers (2)

anastaciu
anastaciu

Reputation: 23822

Just for the sake of completion, if the values are to be in 1 intervals you can define only the first value:

enum COMP
{
    LessThan = -1,
    Equal, // will be 0
    GreaterThan // will be 1
};

Upvotes: 2

dbush
dbush

Reputation: 224207

What you have is an enum, not a union. And what it seems like you're asking is if you can assign specific values to enum constants. You can do so like this:

enum COMP { 
  LessThan=-1, 
  Equal=0, 
  GreaterThan=1 
};

Also, enums are considered integer types, so you can safely convert to or from int.

Upvotes: 6

Related Questions