Home »
C++ programming language
(Enumeration) enum with example in C++
In this article we will learn about enumeration, which is a user defined data type. We use ‘enum' keyword for its implementation. It is related to #define preprocessors in C/C++. It can also be defined to represent integer numbers.
Let's understand by comparing it with #define preprocessor
For example:
#define JAN 1
#define FEB 2
#define MAR 3
#define APR 4
These statements are defining 1, 2, 3 and 4 by constant name JAN, FEB, MAR and APR respectively. Here we need to define each value separately.
But, in case of "enum" there is no need define each value. We can define and access different values (but integral/integer types) by a name that is known as "enumeration".
What is enumeration (enum) in C++?
It is a distinct type of set of values, whose values come between ranges of values.
Reference: http://en.cppreference.com/w/cpp/language/enum
Declare/define enumeration
We can declare/define "enumeration/enum" given as below:
enum month{ JAN=1,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,AUG,SEP,OCT,NOV,DEC}months;
enum week{SUN=1,MON,TUE,WED,THU,FRI,SAT}days;
enum bool{FALSE=0,TRUE};
enum escSeq{BACKSPACE='\b',NEWLINE='\n',HTAB='\t',VTAB='\v',RETURN='\r'};
Note: The most important advantage of "enum" over macro is: "enum" has its scope. That means "enum is only visible within the block it was declared."
Example of C++ enumeration
#include <iostream>
using namespace std;
int main()
{
enum week{SUN=1,MON,TUE,WED,THU,FRI,SAT};
enum week day;
day = THU;
cout<<"Week day number : "<<day<<endl;
return 0;
}
Output
Output
Week day number : 5