0

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!

5
  • 6
    Have you tried it yourself? That's not a bad starting point if you want to find out what something does.
    – user142162
    Commented Jan 3, 2012 at 16:17
  • It won't "do" anything; there are no side effects. But it is perfectly legal C. Commented Jan 3, 2012 at 16:18
  • If your compiler chooses to make the enum wide enough to be able to take values in the range 0 to 19 (most likely), your code will overwrite the value autumn (same as 3) with 19 in the object curr_season; otherwise it is UB and anything can happen.
    – pmg
    Commented Jan 3, 2012 at 16:18
  • @pmg: I think "always" rather than "likely". An enum must be at least as big as a char. Commented Jan 3, 2012 at 16:21
  • Ah, the disappointment of C enum........ Commented Jan 3, 2012 at 16:24

3 Answers 3

4
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;

}
3

Enums constants are of type int in c. Although enums are not explicitly of type int, the conversion between enumerated types, and ints 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;
3
  • 1
    enum constants are of type int, but enum types are implementation defined integer types.
    – ouah
    Commented Jan 3, 2012 at 16:21
  • enums are not of type int. Commented Jan 3, 2012 at 16:21
  • But in c they are freely convertable to int Commented Jan 3, 2012 at 16:27
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.