Topic 27 of 83
Enums
Overview
Enums assign readable names to integer constants, making code much more legible. `enum class` (C++11) provides strongly-typed, scoped enums.
Syntax
cpp
// Old C-style Enum
enum Color { RED, GREEN, BLUE }; // RED=0, GREEN=1...
Color c = RED;
// Modern C++ Scoped Enum (enum class)
enum class Status { PENDING, APPROVED, REJECTED };
Status s = Status::APPROVED;Common Pitfalls
- Trying to print an `enum class` directly to `cout`. It won't implicitly cast to an int; you must cast it explicitly: `static_cast<int>(Status::APPROVED)`.
Interview Tips
- Explain why `enum class` is preferred: Old enums export their variables to the global scope (so you can't have a `RED` in two different enums), and they implicitly convert to integers. `enum class` is scoped and strongly typed.
Real-World Example
Using switch statements with strongly-typed enums.
example
cpp
#include <iostream>
using namespace std;
enum class TrafficLight { RED, YELLOW, GREEN };
int main() {
TrafficLight light = TrafficLight::GREEN;
switch (light) {
case TrafficLight::RED: cout << "Stop\n"; break;
case TrafficLight::YELLOW: cout << "Slow down\n"; break;
case TrafficLight::GREEN: cout << "Go\n"; break;
}
return 0;
}