1. Home
  2. Tutorials
  3. C/C++
  4. C++ Enum
Yolinux.com Tutorial

C/C++ Enum

C and C++ enum syntax and C++ enum classes and examples. Enumeration syntax and use with examples for C and C++.

Enumerations:

The C/C++ enumeration syntax exists to support the use of human readable character names to support a specific list of available values for the specified variable. This is enabled in C and C++ as a set of named integer constants. This can be expressed as #define preprocessor directives or as a C or C++ enumerated type "enum". Both C and C++ use the same enumeration syntax. We also give an example of a C++ enumeration class which extends the capability of the C enumeration.

C / C++ Enumeration Syntax and Example:

Basic C/C++ enumeration declaration and use:

File: enumExample.cpp
01#include <iostream>
02using namespace std;
03 
04main()
05{
06   enum
07   {
08      monday, tuesday, wednesday, thursday, friday, saturday, sunday
09   } day;
10 
11   day = wednesday;
12 
13   if(day == saturday || day == sunday)
14      cout << "Day is a weekend day" << endl;
15   else if(day == wednesday)
16      cout << "Day is hump day - middle of the work week" << endl;
17}
Result: Day is hump day - middle of the work week

Enumerations are represented as incrementing integers beginning with the value 0. One can specify the integer representation of the enumeration by specifying the integer from which the index begins incrementing. More than one enumeration can be represented by the same integer.

File: enumExample2.cpp
01#include <iostream>
02using namespace std;
03 
04main()
05{
06   enum
07   {
08      saturday = 0,
09      sunday = 0,
10      monday,
11      tuesday,
12      wednesday,
13      thursday,
14      friday
15   }  DAY;
16 
17   DAY day = sunday;
18 
19   if(day == 0)
20      cout << "Day is a weekend day" << endl;
21   else if(day == wednesday)
22      cout << "Day is hump day - middle of the work week" << endl;
23}
Result: Day is a weekend day

File: enumExample3.cpp
01#include <iostream>
02using namespace std;
03 
04main()
05{
06   typedef enum
07   {
08      thirteen = 10,
09      fourteen,
10      fifteen,
11      sixteen,
12      seventeen,
13      eighteen,
14      nineteen
15   } TEENS;
16 
17   TEENS teen = seventeen;
18 
19   if(teen == seventeen)
20      cout << seventeen << endl;
21}
Result: 14
Obviously if we started the enumeration at 13 instead of 10 we would have had alignment with the integer in our results.

C++ Enumeration Class:

One can create and enumeration class in C++ to extend the capabilities of enumerations.

File: CDay.hpp
01#ifndef DAY_HPP__
02#define DAY_HPP__
03#include <ostream>
04#include <string>
05#include <algorithm>
06 
07class Day
08{
09public:
10   enum Enum
11   {
12      sunday = 0,
13      monday,
14      tuesday,
15      wednesday,
16      thursday,
17      friday,
18      saturday,
19      InvalidDay
20   };
21 
22   // Constructors
23   Day(void);
24   Day(Enum ee);
25   explicit Day(const std::string& ss);
26 
27   // Overloaded assignment operators
28   Day& operator = (const Day& cc);
29   Day& operator = (const std::string& ss);
30   Day& operator = (Enum ee);
31 
32   // Overloaded comparison operators
33   bool operator<  (const Day& cc) const;
34   bool operator<  (Enum ee) const;
35   bool operator<= (const Day& cc) const;
36   bool operator<= (Enum ee) const;
37   bool operator>  (const Day& cc) const;
38   bool operator>  (Enum ee) const;
39   bool operator>= (const Day& cc) const;
40   bool operator>= (Enum ee) const;
41   bool operator== (const Day& cc) const;
42   bool operator== (const std::string& ss) const;
43   bool operator== (const Enum ee) const;
44   bool operator!= (const Day& cc) const;
45   bool operator!= (const std::string& ss) const;
46   bool operator!= (const Enum ee) const;
47 
48   // Accessor functions
49   inline std::string getString (void) const;
50   inline Enum        getEnum   (void) const;
51   inline int         getValue  (void) const;
52 
53private:
54   // Static functions
55   static Enum        fromString(std::string ss);
56   static std::string toString(Enum ee);
57   static int         toValue(Enum ee);
58 
59   // Data members
60   Enum        m_enum;
61   std::string m_string;
62   int         m_value;
63};
64 
65inline std::ostream& operator<< (std::ostream& _os, const Day& _e)
66{
67   _os << _e.getString();
68   return _os;
69}
70 
71inline std::string Day::getString(void) const
72{
73   return m_string;
74}
75 
76Day::Enum Day::getEnum(void) const
77{
78   return m_enum;
79}
80 
81int Day::getValue(void) const
82{
83   return m_value;
84}
85 
86#endif

File: CDay.cpp
001#include <stdexcept<
002 
003// Constructors
004Day::Day(void) :
005   m_enum(sunday),
006   m_string("Sunday"),
007   m_value(0)
008{}
009 
010Day::Day(Enum _e) :
011   m_enum(_e),
012   m_string(toString(_e)),
013   m_value(0)
014{}
015 
016Day::Day(const std::string& _s) :
017   m_enum(fromString(_s)),
018   m_string(_s),
019   m_value(toValue(m_enum))
020{}
021 
022// Assignment operators
023 
024Day& Day::operator= (const Day& _c)
025{
026   m_string = _c.m_string;
027   m_enum   = _c.m_enum;
028   m_value  = _c.m_value;
029   return *this;
030}
031 
032Day& Day::operator= (const std::string& _s)
033{
034   m_string = _s;
035   m_enum   = fromString(_s);
036   m_value  = toValue(m_enum);
037   return *this;
038}
039 
040Day& Day::operator= (Enum _e)
041{
042   m_enum   = _e;
043   m_string = toString(_e);
044   m_value  = toValue(_e);
045   return *this;
046}
047 
048bool Day::operator< (const Day& _c) const
049{
050   return (m_value < _c.m_value);
051}
052 
053bool Day::operator< (Enum _e) const
054{
055   return (m_value < toValue(_e));
056}
057 
058bool Day::operator<= (const Day& _c) const
059{
060   return (m_value <= _c.m_value);
061}
062 
063bool Day::operator<= (Enum _e) const
064{
065   return (m_value <= toValue(_e));
066}
067 
068bool Day::operator> (const Day& _c) const
069{
070   return (m_value > _c.m_value);
071}
072 
073bool Day::operator> (Enum _e) const
074{
075   return (m_value > toValue(_e));
076}
077 
078bool Day::operator>= (const Day& _c) const
079{
080   return (m_value >= _c.m_value);
081}
082 
083bool Day::operator>= (Enum _e) const
084{
085   return (m_value >= toValue(_e));
086}
087 
088bool Day::operator== (const Day& _c) const
089{
090   return (m_enum == _c.m_enum);
091}
092 
093bool Day::operator== (const std::string& _s) const
094{
095   return (m_string == _s);
096}
097 
098bool Day::operator== (const Enum _e) const
099{
100   return (m_enum == _e);
101}
102 
103bool Day::operator!= (const Day& _c) const
104{
105   return (m_enum != _c.m_enum);
106}
107 
108bool Day::operator!= (const std::string& _s) const
109{
110   return (m_string != _s);
111}
112 
113bool Day::operator!= (const Enum _e) const
114{
115   return (m_enum != _e);
116}
117 
118Day::Enum Day::fromString(std::string _s)
119{
120   // Case insensitive - make all upper case
121   transform(_s.begin(), _s.end(), _s.begin(), toupper);
122   if(_s == "SUNDAY")         return sunday;
123   else if(_s == "MONDAY")    return monday;
124   else if(_s == "TUESDAY")   return tuesday;
125   else if(_s == "WEDNESDAY") return wednesday;
126   else if(_s == "THURSDAY"return thursday;
127   else if(_s == "FRIDAY")    return friday;
128   else if(_s == "SATURDAY"return saturday;
129 
130   throw std::range_error("Not a valid Day value: " + _s);
131   return InvalidDay;
132};
133 
134std::string Day::toString(Day::Enum _e)
135{
136   switch (_e)
137   {
138      case sunday:    { return "SUNDAY";    }
139      case monday:    { return "MONDAY";    }
140      case tuesday:   { return "TUESDAY";   }
141      case wednesday: { return "WEDNESDAY"; }
142      case thursday:  { return "THURSDAY";  }
143      case friday:    { return "FRIDAY";    }
144      case saturday:  { return "SATURDAY";  }
145   }
146   return "InvalidDay";
147}
148 
149int Day::toValue(Day::Enum _e)
150{
151   switch (_e)
152   {
153      case sunday:    { return 0; }
154      case monday:    { return 2; }
155      case tuesday:   { return 3; }
156      case wednesday: { return 4; }
157      case thursday:  { return 5; }
158      case friday:    { return 6; }
159      case saturday:  { return 7; }
160   }
161   return 8;  // Invalid
162}

File: dayProg.cpp
01#include <iostream>
02#include "CDay.hpp"
03using namespace std;
04 
05main()
06{
07   Day day;
08 
09   day = "Saturday";
10 
11   if(day == Day::saturday || day == Day::sunday)
12      cout << "Day is a weekend day" << endl;
13}
Compile: g++ CDay.cpp dayProg.cpp
Results: Day is a weekend day

Other Methodologies:

Associated string array:

File: enumExample5.cpp
01#include <iostream>
02 
03typedef enum
04{
05   monday, tuesday, wednesday, thursday, friday, saturday, sunday
06} Day;
07 
08const char *day_str[]={ "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday", "Sunday" };
09 
10using namespace std;
11 
12main()
13{
14   Day day = saturday;
15 
16   if(day == saturday || day == sunday)
17      cout << day_str[day] << endl;
18}
Compile: g++ enumExample5.cpp
Run: ./a.out
Result: Saturday

C define macros:

File: enumExample6.cpp
01#include <iostream>
02 
03#define SUNDAY    0
04#define MONDAY    1
05#define TUESDAY   2
06#define WEDNESDAY 3
07#define THURSDAY  4
08#define FRIDAY    5
09#define SATURDAY  6
10 
11using namespace std;
12 
13main()
14{
15   int day;
16 
17   day = SATURDAY;
18 
19   if(day == SATURDAY || day == SUNDAY)
20      cout << "Day is a weekend day" << endl;
21}
Compile: g++ enumExample6.cpp
Run: ./a.out
Result: Day is a weekend day

Other methodologies could include STL Map or Boost smart_enum constructs.

Books:

C++ How to Program
by Harvey M. Deitel, Paul J. Deitel
ISBN #0131857576, Prentice Hall

Fifth edition. The first edition of this book (and Professor Sheely at UTA) taught me to program C++. It is complete and covers all the nuances of the C++ language. It also has good code examples. Good for both learning and reference.

Amazon.com
Exceptional C++: 47 Engineering Puzzles, Programming Problems and Solutions
by Herb Sutter
ISBN #0201615622, Addison-Wesley Professional

Advanced C++ features and STL.

Amazon.com
More Exceptional C++
by Herb Sutter
ISBN #020170434X, Addison-Wesley Professional

Amazon.com
Effective C++: 50 Specific Ways to Improve Your Programs and Design (2nd Edition)
by Scott Meyers
ISBN #0201924889, Addison-Wesley Professional

Amazon.com
More Effective C++: 35 New Ways to improve your Programs and Designs
by Scott Meyers
ISBN #020163371X, Addison-Wesley Professional

Amazon.com