I have this enum:
enum Seasons{
winter,spring,summer,autumn
};
what will this code do?
enum Seasons curr_season;
curr_season = autumn;
curr_season = 19;
Thank you!
enum Seasons{
winter,spring,summer,autumn
};
The above creates the following
winter=0, spring=1, summer=2 and autumn=3
NOTE: enums
are just integers! .. It can take negative numbers also!
enum Seasons curr_season;
curr_season = autumn;
/* curr_season will now have 3 assigned */
curr_season = 19;
/* curr_season will now have 19 assigned */
You can run the following code to check this!
#include <stdio.h>
enum Seasons{
winter,spring,summer,autumn
};
void print_seanons(void)
{
printf("winter = %d \n", winter);
printf("spring = %d \n", spring);
printf("summer = %d \n", summer);
printf("autumn = %d \n", autumn);
return;
}
int main(void)
{
enum Seasons curr_season;
print_seanons();
curr_season = autumn;
printf("curr_season = %d \n", curr_season);
curr_season = 19;
printf("curr_season = %d \n", curr_season);
return 0;
}
Enums constants are of type int
in c. Although enum
s are not explicitly of type int
, the conversion between enumerated types, and int
s is silent. There is usually no constraint checking on enums, so your code is functionally equivalent to:
int curr_season;
curr_season = 3;
curr_season = 19;
Enums are integral values, so it will assign the value 19 to curr_season
.
Cross use (assigning integer values to an enum) is considered poor programming practice and should be avoided.
autumn
(same as3
) with19
in the objectcurr_season
; otherwise it is UB and anything can happen.char
.