cpp / intermediate
Snippet
Scoped Enumerations for Type Safety
Unlike traditional C-style enums, 'enum class' prevents name collisions and accidental implicit conversions to integers, providing stronger type safety.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
enum class TrafficLight { Red, Yellow, Green };int main() {TrafficLight signal = TrafficLight::Red;// if (signal == 0) // Error: No implicit conversion to intif (signal == TrafficLight::Red) {return 0;}return 1;}
Breakdown
1
enum class TrafficLight
Declares a scoped enumeration that requires the 'TrafficLight::' prefix.
2
if (signal == 0)
This line is invalid because scoped enums do not automatically convert to numerical types.