Enumerations and State
Enum Basics
An enum gives names to a small set of related choices.
Enum Basics
enum_basics.cpp
#include <iostream>
#include <string>
enum TrafficLight {
Red,
Yellow,
Green
};
std::string describe(TrafficLight light) {
if (light == Red) {
return "stop";
}
if (light == Yellow) {
return "slow";
}
return "go";
}
int main() {
TrafficLight light = ;
std::string action = describe(light);
std::cout << "light=" << light << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
#include <iostream>
#include <string>
enum TrafficLight {
Red,
Yellow,
Green
};
std::string describe(TrafficLight light) {
if (light == Red) {
return "stop";
}
if (light == Yellow) {
return "slow";
}
return "go";
}
int main() {
TrafficLight light = ;
std::string action = describe(light);
std::cout << "light=" << light << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
#include <iostream>
#include <string>
enum TrafficLight {
Red,
Yellow,
Green
};
std::string describe(TrafficLight light) {
if (light == Red) {
return "stop";
}
if (light == Yellow) {
return "slow";
}
return "go";
}
int main() {
TrafficLight light = ;
std::string action = describe(light);
std::cout << "light=" << light << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
unscoped enum
An unscoped enum creates named constants that can be used instead of plain numbers.