0 day streak
cpp / intermediate
Snippet

Scoped Enumerations for Explicit State

Scoped enumerations ('enum class') prevent name collisions by requiring the scope operator. They are also strongly typed, meaning they won't implicitly convert to integers, which catches common logic errors during compilation.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
enum class ConnectionStatus {
Disconnected,
Connecting,
Connected
};
int main() {
ConnectionStatus current = ConnectionStatus::Connecting;
// Strongly typed: cannot be implicitly compared to integers
if (current == ConnectionStatus::Connecting) {
std::cout << "Establishing link..." << std::endl;
}
return 0;
}
Breakdown
1
enum class ConnectionStatus
Defines a scoped enum. Values must be prefixed with 'ConnectionStatus::'.