Is it legal to assign an int to an enum type as shown in c.color = 1? I ran this code and it does seem to set c.color to BLUE as BYE is printed, but I wanted to understand if this actually sets the enum correctly.
typedef enum {
GREEN = 0,
BLUE
}COLOR;
typedef struct{
COLOR color;
}COLORS;
int main()
{
COLORS c;
c.color = 1;
if(c.color == BLUE)
{
printf("BYE");
}
}
enum
, in addition to being an integer type, creates global constants that can, in return, be used to set the enum to any one of the values using the convenient constant as opposed to using a magic number, e.g.enum direction { NORTH, WEST, SOUTH, EAST }; direction = SOUTH; switch direction { case NORTH: /* do suff */ break; case WEST: /* do stuff */ break; ...
You can use anenum
for the purpose of declaring global constants independent of whether you use theenum
later in your code, e.g.enum { MAXC = 128, MAXN = 512 };