Cpp - Data Type enum Definition

Introduction

Enumerated constants create a set of constants with a single statement.

You can use keyword enum and a series of comma-separated names surrounded by braces to create enum type:

enum COLOR { RED, BLUE, GREEN, WHITE, BLACK }; 

This statement creates a set of enumerated constants named COLOR with five values named RED, BLUE, GREEN, WHITE and BLACK.

Internally, enumerated constants hold integer values.

The values begin with 0 for the first in the set and count upwards by 1.

So RED equals 0, BLUE equals 1, GREEN equals 2, WHITE equals 3, and BLACK equals 4.

Constants can specify their values using an = assignment operator:

enum Color { RED=100, BLUE, GREEN=500, WHITE, BLACK=700 }; 

This statement sets RED to 100, GREEN to 500, and BLACK to 700. BLUE equals 101 and WHITE equals 501.

The following code uses enumerated constants for the eight compass directions.

Demo

#include <iostream> 

int main() /*www .  ja va  2s.  co  m*/
{ 
    // set up enumeration 
    enum Direction { North, Northeast, East, Southeast, South, 
          Southwest, West, Northwest }; 
 
    // create a variable to hold it 
    Direction heading; 
    // initialize that variable 
    heading = Southeast; 
 
    std::cout << "Moving " << heading << std::endl; 
    return 0; 
}

Result