Enumeration Type
Learn about the user-defined data type in C++.
We'll cover the following
In this lesson, we’ll look at a data type that is defined by the user, known as the enum or enumerated type.
What is the enum data type?
Enumeration or enum type lets us assign names to integral constants. The enum
keyword is used to define an enumeration. It’s just a way to name integer values. This makes our code easier to read and maintain.
We are most likely to use enums when we want to ensure that the value(s) used in the program are from within the limited set of possible values.
Syntax
enum type-name {value1, value2, ... valueN};
The type-name
is the name of the enumeration. The compiler would, by default, assign the first value 0 to value1
, 1 to value2
, 2 to value3
, and so on.
However, we can set a specific value to an enum element as well.
enum type-name {value1 = 4, value2, value3, ... valueN};
If we don’t assign any specific value to any name, it will automatically be assigned the value of their predecessor, + 1. So, value2
would be equal to 5, value3
would be equal to 6, and so on.
For example, we’ve created an enumeration type called coffee
, where latte
, espresso
, cappuccino
, americano
and mocha
are the values of coffee
type. No other value can be part of the coffee
. We’ll define it as follows:
enum coffee {latte, espresso, cappuccino, americano, mocha};
To use this enumerated type, we’ll create an enum
type variable and assign it any of the enum
elements (enumerators). To use the enumerated type coffee
, let’s create the variable favorite
:
// enum type-name variableName;
enum coffee favorite;
Here, favorite
is the object of the enumerated type coffee
. This means favorite
can only have values equal to the enum
elements.
A simple program that demonstrates how enums work is shown below. Click “Run” to see the output of the program.
Get hands-on with 1200+ tech skills courses.