Enumerated Data Types - C++ Data Type

C++ examples for Data Type:enum

Introduction

You can define enum type as follows:

enum class Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

Here's an example that demonstrates some of the things you can do with enumerations:

Demo Code

#include <iostream>
#include <iomanip>
using std::setw;/*from   ww w  .  ja v  a 2 s. c om*/

int main() {
  enum class Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
                                    yesterday{ Day::Monday }, today{ Day::Tuesday },
                                    tomorrow{ Day::Wednesday };
  Day poets_day{ Day::Friday };

  enum class Punctuation : char { Comma = ',', Exclamation = '!', Question = '?' };
  Punctuation ch{ Punctuation::Comma };

  std::cout << "yesterday's value is " << static_cast<int>(yesterday)
    << static_cast<char>(ch) << " but poets_day's is " << static_cast<int>(poets_day)
    << static_cast<char>(Punctuation::Exclamation) << std::endl;

  today = Day::Thursday;                    // Assign a new ...
  ch = Punctuation::Question;               // ... enumerator values
  tomorrow = poets_day;                     // Copy enumerator value

  std::cout << "Is today's value(" << static_cast<int>(today)
   << ") the same as poets_day(" << static_cast<int>(poets_day)
   << ")" << static_cast<char>(ch) << std::endl;

}

Result


Related Tutorials