cpp / intermediate
Snippet
Strongly Typed Scoped Enumerations
Using 'enum class' creates scoped enumerations that do not implicitly convert to integers. This prevents type errors where unrelated enum values are compared or assigned to numeric variables.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>enum class NetworkStatus : uint8_t {Disconnected,Connecting,Connected};void checkStatus(NetworkStatus s) {if (s == NetworkStatus::Connected) {std::cout << "Online" << std::endl;}}
Breakdown
1
enum class NetworkStatus : uint8_t {
Declares a scoped enum and explicitly sets the underlying storage type to an 8-bit unsigned integer.
2
if (s == NetworkStatus::Connected)
Requires the explicit scope operator, making the code more readable and safer.