Last active
August 21, 2023 04:13
-
-
Save moozzyk/273f684f13b32f489c9ea35fea1e4d19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Enums and Exhaustive `switch` statements in C++ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Color color = static_cast<Color>(42); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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