CHAPTER 18

image

Enum

Enum is a user-defined type consisting of a fixed list of named constants. In the example below, the enumeration type is called Color and contains three constants: Red, Green and Blue.

enum Color { Red, Green, Blue };

The Color type can be used to create variables that may hold one of these constant values.

int main(){  Color c = Red;}

In order to avoid naming conflicts the constant can be qualified with the name of the enum.

Color c = Color.Red;

Enum example

The switch statement provides a good example of when enumerations can be useful. Compared to using ordinary constants, the enumeration has the advantage that it allows ...

Get C++ Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.