Skip to main content

Enumerated Type

Overview

An Enumerated type (Enum) is a data type that defines a fixed set of named values. Each value represents a distinct, meaningful constant, making programs easier to read, safer, and less error-prone.

Enums replace mysterious numbers with self-explanatory names.


What Is an Enumerated Type?

An enum:

  • Contains a finite list of identifiers
  • Each identifier maps to a constant value
  • Restricts variables to valid, predefined options

Only the declared values are allowed.


How It Works

Internally, enum values are often stored as integers, but externally they behave as named constants.

Example mapping:

RED   → 0
GREEN → 1
BLUE → 2

The mapping is usually hidden from the programmer.


Enum vs Constants

AspectEnumConstants
Type safetyYesNo
Value restrictionEnforcedNot enforced
ReadabilityHighMedium
NamespaceScopedGlobal

Common Operations

  • Assignment
  • Comparison
  • Iteration over values
  • Conversion to/from integers or strings

Example

Pseudocode

enum Status { NEW, PROCESSING, DONE }

taskStatus = Status.NEW

if taskStatus == Status.DONE:
archiveTask()

Real-world Analogy

An enum is like a menu with fixed choices. You can order anything on the list, but nothing off-menu 🍽️.


Time and Space Complexity

  • Space: O(1)
  • Comparison: O(1)

Use Cases

  • State machines
  • Configuration options
  • Finite categories
  • Error codes
  • Protocol definitions

Advantages

  • Prevents invalid values
  • Improves code readability
  • Easier maintenance

Limitations

  • Fixed at compile time
  • Not suitable for dynamic sets
  • Limited extensibility