Search code examples
ccompiler-constructionenums

Why isn't an enum checked by the C compiler?


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:

  1. For what cases in the C language doesn't the compiler check the value of an enum?
  2. enum constants are not checked for some reason. Why not? What are the reasons?
  3. Since enum is not checked by the compiler, is using enum error-prone? Please explain.

Solution

    1. 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.

    2. 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).

    3. 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.