Why isn't an enum checked by the C compiler?
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:
- C compiler lets the programmer shoot himself in the foot.
- C compiler lets the programmer shoot himself in the foot.
- C compiler lets the programmer shoot himself in the foot.