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");
}
}
An enum is considered an integer type. So you can assign an integer to a variable with an enum type.
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.
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.
Enumerations are similar to classes and, you can have variables, methods, and constructors within them. Only concrete methods are allowed in an enumeration.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With