Enumerations
Enumerations are integer data types that you can create with a limited range of values. Each value is represented by a symbolic constant that may be used in conjunction with variables of the same enumerated type.
Enumerations:
- Are unique integer data types
- May only contain a specified list of values
- Values are specified as symbolic constants
How to Create an Enumeration Type
Syntax
enum typeName {label0, label1,…, labeln}
Where compiler sets label0=0, label1=1, labeln=n
Creates an ordered list of constants. Each label’s value is one greater than the previous label.
Example
|
1
|
enum weekday {SUN, MON, TUE, WED, THR, FRI, SAT}; |
Label Values:
SUN = 0, MON = 1, TUE = 2, WED = 3, THR = 4 , FRI = 5, SAT = 6
Any label may be assigned a specific value. The following labels will increment from that value.
enum typeName {label0 = const0,…, labeln}
Where compiler sets label0=const0, label1=(const0+1),…
Example
|
1
|
enum people {Rob, Steve, Paul = 7, Bill, Gary}; |
Label Values:
Rob = 0, Steve = 1, Paul = 7, Bill = 8, Gary = 9
How to Declare an Enumeration Type Variable
Declared along with type:
Syntax
enum typeName {const-list} varname1…;
Declared independently:
Syntax
enum typeName varName1…,varNamen;
Example
|
1
2
3
|
enum weekday {SUN, MON, TUE, WED, THR, FRI, SAT} today;enum weekday day; //day is a variable of type weekday |
No type name specified:
Syntax
enum {const-list} varName1…,varNamen;
Only variables specified as part of the enum declaration may be of that type. No type name is available to declare additional variables of the enum type later in code.
|
1
|
enum {SUN, MON, TUE, WED, THR, FRI, SAT} today; |
If enumeration and variable have already been defined:
varName = labeln;
The labels may be used as any other symbolic constant. Variables defined as enumeration types must be used in conjunction with the type’s labels or equivalent integer.
Example
|
1
2
3
4
5
6
7
|
enum weekday {SUN, MON, TUE, WED, THR, FRI, SAT};enum weekday day;day = WED;day = 6; //May only use values from 0 to 6if (day == WED){ … |