Enum

From Tux
Jump to: navigation, search

enum can be used to create an enumerated type, which is a datatype in which constants can be named and values are automatically assigned.

If the bool data type did not exist in C++, one could be created and used as follows:

#include <iostream>

enum bool {false, true};
// false is automatically assigned the value 0
// true is automatically assigned the next integral value after false, which is 1

using namespace std;

int main()
{
     bool var = false;

     var = true;

     if (var)
          cout << "This statement will always print" << endl;

     return (0);
}

The datatype can, like structs, be declared globally.

More details:

  • Each identifier in the list of constants must adhere to standard identifier rules
  • The identifier for the data type name must adhere to standard identifier rules
  • Individual constant identifiers can be set equal to specific values and, if this is done, later identifiers without explicit assignments take on the previous identifier's value plus 1 (e.g. with enum mytype {first = 5, second};, second is assigned a value of 6)
  • For much more information, see http://en.cppreference.com/w/cpp/language/enum