Skip to content

Instantly share code, notes, and snippets.

@moozzyk
Last active August 21, 2023 04:13
Show Gist options
  • Save moozzyk/273f684f13b32f489c9ea35fea1e4d19 to your computer and use it in GitHub Desktop.
Save moozzyk/273f684f13b32f489c9ea35fea1e4d19 to your computer and use it in GitHub Desktop.
Enums and Exhaustive `switch` statements in C++
Color color = static_cast<Color>(42);
enum.cpp:12:12: warning: enumeration value 'Yellow' not handled in switch [-Wswitch]
switch(c) {
^
enum.cpp:12:12: note: add missing switch cases
switch(c) {
^
enum.cpp:17:1: warning: non-void function does not return a value in all control paths [-Wreturn-type]
Color convertToColor(int c) {
auto color = static_cast<Color>(c);
switch(color) {
case Color::Red:
case Color::Green:
case Color::Blue:
return color;
}
throw std::runtime_error("Invalid color");
}
#include <iostream>
#include <string>
enum class Color {
Red,
Green,
Blue,
};
std::string getColorName(Color c) {
switch(c) {
case Color::Red: return "red";
case Color::Green: return "green";
case Color::Blue: return "blue";
}
}
int main() {
std::cout << "Color: " << getColorName(Color::Green) << std::endl;
return 0;
}
enum class Color {
Red,
Green,
Blue,
Yellow,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment