$ clang++ main.cpp -std=c++11 -o main && ./main
Converting red to string: red
Converting 2 to enum to string: yellow
Converting 20 to enum to string: undefined
Converting 20 to enum to int: 20
Created
June 27, 2019 17:52
-
-
Save JoshuaGross/3b22e020a8779b36e0e0df61200dff33 to your computer and use it in GitHub Desktop.
Enum conversion undefined behavior in C++
This file contains hidden or 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
#import <iostream> | |
enum Color : int { red = 1, yellow = 2, green = 4, grey = 17, ranch_dressing = 42 }; | |
std::string colorToString (Color x) { | |
switch (x) { | |
case red: return "red"; | |
case yellow: return "yellow"; | |
case green: return "green"; | |
case grey: return "grey"; | |
case ranch_dressing: return "ranch_dressing"; | |
default: return "undefined"; | |
} | |
} | |
int main (int argc, char** argv) { | |
Color x = red; | |
std::cout << "Converting red to string: " << colorToString(x) << std::endl; | |
Color y = static_cast<Color>(2); | |
std::cout << "Converting 2 to enum to string: " << colorToString(y) << std::endl; | |
Color z = static_cast<Color>(20); | |
std::cout << "Converting 20 to enum to string: " << colorToString(z) << std::endl; | |
std::cout << "Converting 20 to enum to int: " << (int)(z) << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment