Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we typecast a enum variable In c

Tags:

c

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.

like image 761
Amit Singh Tomar Avatar asked Nov 04 '11 16:11

Amit Singh Tomar


2 Answers

Yes. In C enum types are just ints 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 */
like image 193
linuxuser27 Avatar answered Oct 14 '22 11:10

linuxuser27


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.

like image 34
Jens Gustedt Avatar answered Oct 14 '22 13:10

Jens Gustedt