1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M4 Enums
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
14Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M4 Enums

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
14Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Enums

Overview

If a video game character can be in 3 states: Menu, Playing, or Dead. You could use integers (0 = Menu, 1 = Playing, 2 = Dead), but writing if (state == 2) makes the code totally unreadable and highly prone to bugs.

An Enum (Enumeration) is a custom data type that allows you to assign human-readable English names to underlying integers. By default, the compiler assigns the first item to 0, the second to 1, and so on. Modern C++ heavily relies on enum class (Scoped Enums) because they enforce strict type safety, ensuring you can't accidentally add a Menu state to a Dead state.

Syntax

cpp
// --- 1. OLD C-STYLE ENUM (Unsafe, avoid) ---
enum Difficulty { EASY, NORMAL, HARD };
// Behind the scenes: EASY = 0, NORMAL = 1, HARD = 2

// --- 2. MODERN SCOPED ENUM CLASS (Safe) ---
enum class GameState {
    MENU,
    PLAYING,
    GAMEOVER
};

int main() {
    // Requires the scope resolution operator (::)
    GameState current = GameState::PLAYING;
    
    if (current == GameState::GAMEOVER) {
        // Handle death
    }
    return 0;
}

Common Pitfalls

  • Using standard enum instead of enum class. Standard enums 'leak' their variable names into the global scope. If you have enum TrafficLight { RED } and enum AlertLevel { RED }, the compiler crashes because 'RED' is defined twice. enum class solves this natively.
  • Trying to print an Enum directly to the terminal. cout << GameState::MENU causes a massive compiler error for enum class. Enums are strict mathematical constructs, not strings. You must cast it to an integer or use a switch to print strings.

Interview Questions

Why does the C++ community universally recommend enum class over the legacy C-style enum?

enum class provides two critical features: Scope and Strong Typing. The values are safely trapped inside their scope (preventing naming collisions like 'RED'), and they will not implicitly convert to integers. This prevents catastrophic logic bugs, like accidentally passing a 'TrafficLight::GREEN' into a function expecting a 'FileStatus::SUCCESS'.

Real-World Example

Using enum class with a switch statement for blazing fast, highly readable State Machines.

example
cpp
#include <iostream>

enum class Weapon { SWORD, BOW, MAGIC };

int main() {
    Weapon equipped = Weapon::BOW;
    
    // The compiler optimizes this into a high-speed Jump Table
    switch (equipped) {
        case Weapon::SWORD:
            std::cout << "Swing sword!\n";
            break;
        case Weapon::BOW:
            std::cout << "Fire arrow!\n";
            break;
        case Weapon::MAGIC:
            std::cout << "Cast spell!\n";
            break;
    }
    
    return 0;
}

Check Your Knowledge

Test your understanding of Enums with these quick questions.

Question 1

If you declare `enum class Level { LOW = 10, MEDIUM, HIGH };`, what is the underlying integer value assigned to HIGH by the compiler?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Enums

Overview

If a video game character can be in 3 states: Menu, Playing, or Dead. You could use integers (0 = Menu, 1 = Playing, 2 = Dead), but writing if (state == 2) makes the code totally unreadable and highly prone to bugs.

An Enum (Enumeration) is a custom data type that allows you to assign human-readable English names to underlying integers. By default, the compiler assigns the first item to 0, the second to 1, and so on. Modern C++ heavily relies on enum class (Scoped Enums) because they enforce strict type safety, ensuring you can't accidentally add a Menu state to a Dead state.

Syntax

cpp
// --- 1. OLD C-STYLE ENUM (Unsafe, avoid) ---
enum Difficulty { EASY, NORMAL, HARD };
// Behind the scenes: EASY = 0, NORMAL = 1, HARD = 2

// --- 2. MODERN SCOPED ENUM CLASS (Safe) ---
enum class GameState {
    MENU,
    PLAYING,
    GAMEOVER
};

int main() {
    // Requires the scope resolution operator (::)
    GameState current = GameState::PLAYING;
    
    if (current == GameState::GAMEOVER) {
        // Handle death
    }
    return 0;
}

Common Pitfalls

  • Using standard enum instead of enum class. Standard enums 'leak' their variable names into the global scope. If you have enum TrafficLight { RED } and enum AlertLevel { RED }, the compiler crashes because 'RED' is defined twice. enum class solves this natively.
  • Trying to print an Enum directly to the terminal. cout << GameState::MENU causes a massive compiler error for enum class. Enums are strict mathematical constructs, not strings. You must cast it to an integer or use a switch to print strings.

Interview Questions

Why does the C++ community universally recommend enum class over the legacy C-style enum?

enum class provides two critical features: Scope and Strong Typing. The values are safely trapped inside their scope (preventing naming collisions like 'RED'), and they will not implicitly convert to integers. This prevents catastrophic logic bugs, like accidentally passing a 'TrafficLight::GREEN' into a function expecting a 'FileStatus::SUCCESS'.

Real-World Example

Using enum class with a switch statement for blazing fast, highly readable State Machines.

example
cpp
#include <iostream>

enum class Weapon { SWORD, BOW, MAGIC };

int main() {
    Weapon equipped = Weapon::BOW;
    
    // The compiler optimizes this into a high-speed Jump Table
    switch (equipped) {
        case Weapon::SWORD:
            std::cout << "Swing sword!\n";
            break;
        case Weapon::BOW:
            std::cout << "Fire arrow!\n";
            break;
        case Weapon::MAGIC:
            std::cout << "Cast spell!\n";
            break;
    }
    
    return 0;
}

Check Your Knowledge

Test your understanding of Enums with these quick questions.

Question 1

If you declare `enum class Level { LOW = 10, MEDIUM, HIGH };`, what is the underlying integer value assigned to HIGH by the compiler?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A