Enumeration Data Types
Introduction
- Enumeration
(enum) is a user-defined data type in C++.
- create
a set of named integral constants under a single type name.
- Improves
readability and maintainability by replacing numeric codes
with meaningful names.
Syntax
enum enum_name { value1, value2, value3, ... };
- enum
→ keyword to define an enumeration.
- enum_name
→ the name of the new enumeration type.
- value1,
value2, ... → identifiers representing integer constants.
Default
Behavior
- By
default, the first enumerator has value 0, the next 1, and
so on.
- explicitly
assign values.
Example – Basic Enumeration
#include <iostream>
using namespace std;
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };
int main() {
Day today = WED;
cout <<
"Today is day number: " << today << endl;
return 0;
}
Output:
Today is day number: 2
Explanation: MON=0, TUE=1, WED=2, etc.
Example 2 – Custom Values
#include <iostream>
using namespace std;
enum Month { JAN=1, FEB=2, MAR=3, APR=4, MAY=5, JUN=6,
JUL=7, AUG=8, SEP=9, OCT=10, NOV=11, DEC=12 };
int main() {
Month birthMonth =
DEC;
cout <<
"Birth month number: " << birthMonth << endl;
return 0;
}
Output:
Birth month number: 12
============================================================
0 Comments