An enumeration is a programmer-defined data type that can take on a finite set of user-specified values. The values that an enumerated type can hold are all stored as integer values. However, they are generally specified in the program by the more user-friendly names given in the type definition.
The default integer value of the first enumerated value is 0 and the value for any other is 1 more than the previous value. However, the programmer can specify any integer values that he would like, including repeated values and formulas that use prior values.
Example 1
// We can define an enum to represent boolean values. // In this case, keFalse = 0 and keTrue = 1. enum EBool {keFalse, keTrue}; // Create an instance of the type and assign it the value keTrue. EBool eMyBool = keTrue;
Example 2
// We can define an enum to represent colors. // In this case, keRed = 0, keBlue = 1, keYellow = 2. enum EColor {keRed, keBlue, keYellow}; // Create an instance of the type and assign it the value keRed. EColor eMyColor = keRed;
Example 3
// We can define an enum to represent some prime numbers. // Unspecified values are one more than the previous value. // In this case, keTwo = 2, keThree = 3, keFive = 5, keSeven = 7. enum EPrimeNum {keTwo = 2, keThree, keFive = 5, keSeven = 7}; // Create an instance of the type and assign it the value keThree. EPrimeNum eMyPrime = keThree;
Example 4
// We can define an enum to represent bits. // We can use formulas and the previous values to assign new values. // Here, we use the bit shift to set keZero = 1, keOne = 2, keTwo = 4. enum EBit {keZero = 1, keOne = keZero << 1, keTwo = keOne << 1}; // Create an instance of the type and assign it the value keTwo. EBit eMyBit = keTwo;
Example 5
// We can define an enum to represent numbers of a Fibonacci sequence. // We can use formulas and the previous values to assign new values. // In this case, keF1 = 1, keF2 = 1, keF3 = 2, keF4 = 3. enum EFibonacci {keF1 = 1, keF2 = keF1, keF3, keF4 = keF2 + keF3}; // Create an instance of the type and assign it the value keF4. EFibonacci eMyFib(keF4);
© 20072025 XoaX.net LLC. All rights reserved.