I have been asked this question in interview:
Is it possible to typecast a enum variable to some other type?
I really don't know how to answer it.
Yes. In C enum
types are just int
s under the covers. Typecast them to whatever you want.
enum cardsuit {
Clubs = 1,
Diamonds,
Hearts,
Spades
};
enum cardsuit trump = Diamonds;
int d = (int)trump; /* 'd' would be 2 */
Any enum
expression in C can be converted to any arithmetic type, that are integers or floating points of any sort and pointers. E.g this is valid in C:
const enum { nullpointer } nullpointer_variable = nullpointer;
unsigned *p = nullpointer; // initialization with an int
unsigned *p = nullpointer_variable; // initialization with an enum expression
Most of the time you would not even need an explicit cast.
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