19.4. Enumerations

[ fromfile: enums.xml id: enums ]

 enum {UNKNOWN=0, JAN=1, FEB=2, MAR=3}; 
 enum Ages {MANNY = 10, MOE, JACK = 23, 
           SCOOTER = JACK + 10};
 enum Winter {JAN=1, FEB, MAR, MARCH = MAR }; 
     Winter m = JAN;
     int i = JAN;   // OK - enum can be implicitly converted to int.
     m = i;         // error - explicit cast is required.
     m = static_cast<Winter>(i);  // OK
     i = m;         // OK
     m = 4;         // error

Example 19.3. src/enums/enumtst.cpp

#include <iostream>
using namespace std;

int main(int, char** ) {
    enum Signal { off, on } sig;            1
    sig = on;
    enum Answer { no, yes, maybe = -1 };    2
    Answer ans = no;                        3
//    enum Neg {no,false} c;                4
    enum { lazy, hazy, crazy } why;         5
    int  i, j = on;                         6
    sig = off;  
    i = ans; 
//  ans = s                                 7
    ans = static_cast<Answer>(sig);         8
    ans = (sig ? no : yes); 
    sig = static_cast<Signal>(9);           9
    Signal sig2(sig);                       10
    why = hazy;
    cout << "sig2, ans, i, j, why "
         << sig2 << ans << i << j << why << endl;
    return 0;
}

Output:

src/enums> ./enums
sig2, ans, i, j, why 91011
src/enums>



1

A new type, 2 new enum identifiers, and a variable definition all in one line.

2

Just the type/enum definitions.

3

An instance of an enum.

4

Illegal redefinitions of identifiers.

5

An unnamed enum variable.

6

An enum can always convert to int.

7

Conversions between enum types cannot be done implicitly.

8

Conversion is okay with a cast.

9

Bad news!

10

Have we added an unnamed enumerator?