Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign values to enum in C

Tags:

c

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");
    }
}
like image 802
Smiley7 Avatar asked Aug 10 '17 01:08

Smiley7


People also ask

Can we assign values to enum in C?

An enum is considered an integer type. So you can assign an integer to a variable with an enum type.

How does C assign enum values?

If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1, and so on.

Can we assign value to enum?

You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.

Can we declare variables in enum?

Enumerations are similar to classes and, you can have variables, methods, and constructors within them. Only concrete methods are allowed in an enumeration.


2 Answers

An enum is considered an integer type. So you can assign an integer to a variable with an enum type.

From section 6.2.5 of the C standard:

16 An enumeration comprises a set of named integer constant values. Each distinct enumeration constitutes a different enumerated type .

17 The type char , the signed and unsigned integer types, and the enumerated types are collectively called integer types . The integer and real floating types are collectively called real types .

like image 106
dbush Avatar answered Nov 13 '22 01:11

dbush


From the CPP Reference website,

Each enumerated type is compatible with one of: char, a signed integer type, or an unsigned integer type. It is implementation-defined which type is compatible with any given enumerated type, but whatever it is, it must be capable of representing all enumerator values of that enumeration.

You should be fine assigning an enum an integer value.

like image 1
TimD1 Avatar answered Nov 13 '22 00:11

TimD1