C++ Enumeration (enum)

In C++, an enumeration (enum) is a special data type that represents a set of constant values. It allows for better readability when working with predefined categories or states.

Tutorials dojo strip

Defining an Enum

To create an enum. use the enum keyword followed by its name and a list of constants inside curly braces {}.

Example: Declaring an Enum

C++

This enum groups three constant values:

  • OFF (default value 0)
  • IDLE (default value 1)
  • RUNNING (default value 2)

Using an Enum

To work with an enum, declare a variable of its type.

Example: Assigning and Printing Enum Values

C++

Since IDLE is the second item, its default value is 1.

Customizing Enum Values

By default, enums start at 0 and increment by 1, but you can assign custom values.

Example: Custom Enum Values

C++

Custom values help improve clarity in programs.

Automatic Value Increment

If you set a value for one item, the next ones automatically increase.

Example

C++

Using Enum in a switch Statement

Enums are often used in switch cases for structured decision-making.

Example: Evaluating Engine Status

C++
Tutorials dojo strip