An enum type provides a way to restrict a variable to one of a fixed set of values.
enum rainbowcolor {red,orange,green, yellow, blue,indigo,violet};By default these are assigned the values 0 to 6 (red is 0, violet is 6). You can define your own values instead of using the compiler values e.g.
enum rainbowcolor {red=1000,orange=1005,green=1009, yellow=1010, blue,indigo,violet};The remaining unassigned colors will be assigned 1011, 1012 and 1013. The values continue sequentially from the last assigned value which was yellow=1010.
You can assign an enum value to an int as in
int p=red;but not the other way round. That's the restriction and it prevents assignment of meaningless values. Even assigning a value that corresponds to an enum constant is an error.
rainbowcolor g=1000; // Error!The requires
rainbowcolor g=red;This is type safety in action. Only valid values of the enumeration range can be assigned. This is part of the general C++ philosophy that it is better for the compiler to catch errors at compile time than the user at runtime.
Even though the two statements are conceptually the same. In fact you'll usually find that these two seemingly identical lines
int p =1000;are both likely to have identical machine code generated by the compiler. Certainly they do in Microsoft Visual C++.
rainbowcolor r = red;
That completes this tutorial. The next tutorial is about expressions and statements.

