The following text is an excerpt from C Programming Language, 2nd Edition, written by the creator of the C language (so I presume it is correct):
Although variables of enum types may be declared, compilers need not check that what you store in such a variable is a valid value for the enumeration.
I have some doubts:
enum
?enum
constants are not checked for some reason. Why not? What are the reasons? enum
is not checked by the compiler, is using enum
error-prone? Please explain.Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.
Enumeration "values" aren't stored at all, as they are compile-time named constants. The compiler simply exchanges the use of an enumeration symbol, with the value of it. Also, the type of an enumeration value is of type int , so the exact size can differ.
You can't do that. A C enum is not much more than a bunch of constants. There's no type-safety or reflection that you might get in a C# or Java enum . Save this answer.
An enumeration is like a fancy integer, and it's better than defining a whole load of constants or preprocessor macros as names for the constant values you want to store, because a compiler (or editor) can check that you're using the right names and values to go with the right type. On the other hand, being just an int, there's nothing stopping you putting in a value you didn't make a name for, which is occasionally useful.
They can't be checked in every case. What if you add two numbers together to get the value that's going to be put in the enum-typed variable? It could be any value, generated at runtime, so it can't be checked (without a lot of overhead, at least).
Everything in C is unsafe; there's practically no feature which the compiler can totally prevent you from abusing. enums are safe because they are effective at preventing programmer error and confusion, not because they stop you doing something stupid.
You can do a enum like
enum status {
ST_READY = 1 << 0, /* 1 */
ST_WAIT = 1 << 1, /* 2 */
ST_ERROR = 1 << 2, /* 4 */
ST_HALT = 1 << 3, /* 8 */
ST_ETC = 1 << 4, /* 16 */
};
Then define an object of that type
enum status status;
and set it to the bitwise OR of some 'simple' statuses
status = ST_WAIT | ST_ERROR; /* recoverable error */
Note that the value ST_WAIT | ST_ERROR
is 6
and that that value is not part of the enum.
To answer your questions:
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