TITLE: Definition for valid enum ranges PROBLEM: mcr@holly.demon.co.uk (Mark Rogers) How about a new syntax enum small_int { MaxInt = -128, ... , MaxInt = 128 }; where ... says that all values between -128 and 128 are valid small_int's, but don't have names? RESPONSE: steve@taumet.com (Steve Clamage), 31 May 93 This situation has already been addressed by the C++ Committee via a semantic (not syntax) extension of enums. The current rule about enums says assigning a value other than an enumerator of the same type to an enum variable has undefined results. (Few, if any, compilers warn about this, or give unexpected results.) The new rule states (loosely worded) that if N bits are required to hold the range of the enum values, then all values expressible in N bits are valid for objects of that enum type. (The obvious things about sign and 1's complement versus 2's complement have to be taken into account.) Example: enum Colors { red = -5, green = 0, blue = 13 } color; enum Tastes { sweet = 1, salty = 3, sour = 5, bitter = 7 } taste; It takes 5 bits, including the sign bit, to hold a value of type Colors. It takes 3 bits for Tastes, since no negative values are involved. Under the new rule, the following statements are all legal and well-defined: color = Colors(-15); // always in range color = Colors(blue+2); taste = Tastes(4); taste = Tastes(0); But not necessarily: color = Colors(-16); // out of range if 1's complement taste = Tastes(sweet-2); // out of range (no negative Tastes) taste = Taste(8); // out of range (too many bits) [ If you have ever wondered, as I have, why you cannot have a forward declaration for an enum (especially useful for enums within a class scope), here's your answer. -adc ]