2

I am using enumerated type declaration. I can't print it.

So far I have written the following code. The question is how to print a enum type variable?

#include <stdio.h>
int main()    
{    
    enum day {monday,tuesday,wednwsday,thrusday,friday,saturday,sunday};    
    enum day week_st, week_end;
    week_st = monday;
    week_end = friday;
    if(week_st == monday)
    {
        printf("%s\n",week_end);
    }
    return 0;
}
Sourav Das
  • 527
  • 2
  • 5
  • 13

4 Answers4

2

There are couple of ways to print the enum.

  1. Print it as an integer. This is the simple option.

    printf("%d",week_end);
    
  2. Print a string representation of it. This option requires a way to map the integer value of the enum to a string.

    Define an array of strings.

    char const* weekDays[] = {"Monday", ..., "Saturday", "Sunday"};
    

    Use the array of strings and the enum to print a string.

    printf("%s",weekDays[week_end]);
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

you cant use enum like that,

 enum day {monday,tuesday,wednwsday,thrusday,friday,saturday,sunday};

your this line will initialize the values like this

monday=0;

tuesday=1; and so on

enum day week_st, week_end;

your this line will declare two objects enum day ,Enumerators are used for giving constant values to the variables;

not displaying character string.

Community
  • 1
  • 1
smali
  • 4,687
  • 7
  • 38
  • 60
1

enum is not string. printf("%d", week_end) will output:4

reference http://www.cplusplus.com/doc/tutorial/other_data_types/ : "Values of enumerated types declared with enum are implicitly convertible to the integer type int, and vice versa. In fact, the elements of such an enum are always assigned an integer numerical equivalent internally, of which they become an alias. If it is not specified otherwise, the integer value equivalent to the first possible value is 0, the equivalent to the second is 1, to the third is 2, and so on... Therefore, in the data type colors_t defined above, black would be equivalent to 0, blue would be equivalent to 1, green to 2, and so on..."

hang.liu
  • 11
  • 1
0

Type of enum is int so try to print with format specifier of int Printf("%d",week_end);

But in your code if condition is evaluated to false so it it won't go to print statement