How do I use enum and enum class in C++?

In C++, enumeration (enum) is a user-defined data type that consists of integral constants. It helps to represent a set of named integer values. In C++11 and later, enum class was introduced to provide better type safety and scoping for enumeration types.

Using Enum

An ordinary enum allows you to define a set of named integer constants. Here’s an example:

enum Color { Red, Green, Blue }; Color myColor = Red;

Using Enum Class

An enum class requires a scope to access the enumerators and also prevents implicit conversion to integers. Here's an example:

enum class Fruit { Apple, Banana, Cherry }; Fruit myFruit = Fruit::Apple;

C++ enum enum class user-defined data type type safety C++11 programming