Why doesn't the compiler complain when I try to assign incorrect values to variable a
of type enum answer
?
#include <stdio.h>
int main()
{
enum answer {NO, YES};
enum gender {MALE, FEMALE};
enum answer a = 5; /* Assign an invalid value. */
printf("answer: %d\n", a);
a = MALE; /* Assign a value of wrong type */
printf("answer: %d\n", a);
return 0;
}
Here is the output:
$ gcc -std=c99 -pedantic -Wall -Wextra enum.c
$ ./a.out
answer: 5
answer: 0
If enum
doesn't lead to type-checking, then what is the point of having the syntax as:
enum [identifier] {enumerator-list}
I used answer
and gender
as the identifier for my enum. What is the point of allowing this syntax?
I mean this code could be very well written as
enum {NO, YES};
enum {MALE, FEMALE};
What is the point of allowing this syntax?
enum answer {NO, YES};
enum gender {MALE, FEMALE};
Enumerations make for clearer and more readable code, particularly when meaningful names are used. The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future.
The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.
In C++ programming, enum or enumeration is a data type consisting of named values like elements, members, etc., that represent integral constants. It provides a way to define and group integral constants. It also makes the code easy to maintain and less complex.
Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.
Why doesn't the compiler complain when I try to assign incorrect values to variable
a
of typeenum answer
?
Because in C, an enum
is practically equivalent to an int
. It was standarized like it, and simply too many programs rely on that behavior for it to change.
In C++, they are distinct types and the compiler complains:
$ g++ -Wall -Wextra a.c
a.c: In function 'int main()':
a.c:8:24: error: invalid conversion from 'int' to 'main()::answer' [-fpermissive]
a.c:11:14: error: cannot convert 'main()::gender' to 'main()::answer' in assignment
What is the point of allowing this syntax?
My quick guess would be forward compatibility.
C exposes enumeration
values directly as integer while in C++ enum
is a real type. Hence in C++ enum
results in a type check while in C enum just represents constants of type int. Therefore integer and enum values can be intermixed in all the arithmetic operations.
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