Saturday, May 9, 2009

Enum datatype?

enum color {pink,red};


enum color c = 10; //wrong


enum color c = (enum color) 10;//correct





why is the above typecasting allowed for a variable of enum datatype.


if i had to equate something to an integer, i would do the below:


int c;


c = 10; or


c = red;





if c is to be equated to both red and some integer value, c should be declared an integer . if it is going to hold only


the enum value like red or pink, it should be declared of enum type.





Pls illustrate an example when this scenario is valid:


enum color c = (enum color) 10;


and why it cant be substituted by simple int c = 10;





My point is typecasting should be disallowed.

Enum datatype?
When you try to do


enum color c = 10;


the compiler gets to that line of code and says "sorry, color can only be pink or red (which is really just 0 or 1)".





Everytime you typecast something, you're basically telling the compiler "trust me on this, i know what i'm doing", and the compiler just plays along and does as it's told. It may give you a warning, but that's usually about all.





As for why you'd ever assign an enum variable something that is outside of it's defined range... the only reason I can think of, is to make it undefined (ie. no color), but, it's more proper just to have an "undefined" in the enum.


No comments:

Post a Comment