Difference between revisions of "Enum"

From Tux
Jump to: navigation, search
(Created page with "'''<code>enum</code>''' 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 <cod...")
 
 
Line 1: Line 1:
 
'''<code>enum</code>''' can be used to create an '''enumerated type''', which is a datatype in which constants can be named and values are automatically assigned.
 
'''<code>enum</code>''' 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 <code>bool</code> data type did not exist in C++, one could be created and used follows:
+
If the <code>bool</code> data type did not exist in C++, one could be created and used as follows:
  
 
<source lang="cpp">
 
<source lang="cpp">
Line 23: Line 23:
 
     return (0);
 
     return (0);
 
}
 
}
 
 
</source>
 
</source>
  

Latest revision as of 13:19, 27 January 2018

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