techmore.in

C++ Enums

In C++, enums (short for enumerations) are a user-defined data type that consists of a set of named integer constants. They are used to represent a collection of related values, making code more readable and manageable. Enums help in defining a variable that can only take one out of a limited set of values.

1. Basic Syntax

An enumeration is defined using the enum keyword followed by a name and a list of named values enclosed in braces.

Example:

cpp
enum Color { RED, GREEN, BLUE };

In this example, Color is an enumeration type with three possible values: RED, GREEN, and BLUE. By default, the values are assigned integers starting from 0.

2. Customizing Values

You can assign specific values to the named constants in an enumeration.

Example:

cpp
enum Day { MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };

Here, MONDAY is explicitly set to 1, and the subsequent values will increment automatically (i.e., TUESDAY will be 2, WEDNESDAY will be 3, and so on).

3. Using Enums

You can declare variables of the enum type and assign them values from the enum list.

Example:

cpp
#include using namespace std; enum Status { SUCCESS, FAILURE, PENDING }; int main() { Status jobStatus = PENDING; if (jobStatus == SUCCESS) { cout << "Operation was successful!" << endl; } else if (jobStatus == FAILURE) { cout << "Operation failed!" << endl; } else { cout << "Operation is pending." << endl; } return 0; }

4. Enum Classes (Scoped Enums)

In C++11, enum classes (also known as scoped enums) were introduced. They provide better type safety and prevent name clashes by creating a scoped enumeration.

Example:

cpp
enum class Fruit { APPLE, BANANA, CHERRY }; int main() { Fruit myFruit = Fruit::APPLE; if (myFruit == Fruit::APPLE) { cout << "You have an apple." << endl; } return 0; }
  • Scoped enums require the use of the scope resolution operator (::) to access the enumerators (e.g., Fruit::APPLE).
  • They do not implicitly convert to integers, providing better type safety.

5. Underlying Type of Enums

In C++11 and later, you can specify the underlying type of an enum class, which determines the size of the enum values.

Example:

cpp
enum class ErrorCode : unsigned int { OK = 0, WARNING = 1, ERROR = 2 };
  • ErrorCode is an enum class with unsigned int as its underlying type.

6. Accessing Enum Values

To access or print the values of an enum class, you need to cast the enum value to its underlying type.

Example:

cpp
#include using namespace std; enum class Level : int { LOW = 1, MEDIUM = 2, HIGH = 3 }; int main() { Level myLevel = Level::MEDIUM; // Casting to print integer value cout << "The level is: " << static_cast<int>(myLevel) << endl; return 0; }

7. Enum Iteration

C++ does not provide built-in iteration for enums. To iterate over enum values, you can use an array or a function.

Example:

cpp
#include using namespace std; enum class Direction { NORTH, EAST, SOUTH, WEST }; const char* directionToString(Direction dir) { switch (dir) { case Direction::NORTH: return "North"; case Direction::EAST: return "East"; case Direction::SOUTH: return "South"; case Direction::WEST: return "West"; default: return "Unknown"; } } int main() { for (int i = static_cast<int>(Direction::NORTH); i <= static_cast<int>(Direction::WEST); i++) { Direction dir = static_cast(i); cout << directionToString(dir) << endl; } return 0; }

Summary:

  1. Basic Enums:

    • Use the enum keyword to define enumerations with named constants.
    • Values start from 0 by default and increment automatically unless specified.
  2. Custom Values:

    • Assign specific integer values to the enumerators if needed.
  3. Enum Classes:

    • Use enum class for better type safety and scoped enumerations.
    • Access enumerators with the scope resolution operator (::).
  4. Underlying Type:

    • Specify an underlying type for enum classes to control the storage size.
  5. Accessing and Printing:

    • Use casting to access or print enum values.
  6. Iteration:

    • Use arrays or functions to iterate over enum values, as C++ does not provide built-in iteration for enums.

Enums improve code readability by providing meaningful names for integer values, making it easier to understand and maintain code.