Enumerations and State
Enum Basics
An enum gives names to a small set of related choices.
unscoped enum
An unscoped enum creates named constants that can be used instead of plain numbers.
Enum Basics
enum_basics.cpp
Replay: real traced execution (multi-file project)
#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 = Green;
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 = Red;
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 = Yellow;
std::string action = describe(light);
std::cout << "light=" << light << std::endl;
std::cout << "action=" << action << std::endl;
return 0;
}
light ← 2
20int main() {21 TrafficLight light→ 2 = Green; //@light=Red, Yellow2223 std::string action = describe(light2);std::string describe(TrafficLight light)
10std::string describe(TrafficLight light2) {11 if (light == Red) {12 return "stop";13 }14 if (light == Yellow) {15 return "slow";16 }17 return "go";18}action ← go
23 std::string action→ go = describe(light2);2425 std::cout << "light=" << light2 << std::endl;26 std::cout << "action=" << actiongo << std::endl;27 return 0;28}outputlight=2 action=go
light ← 0
20int main() {21 TrafficLight light→ 0 = Red;2223 std::string action = describe(light0);std::string describe(TrafficLight light)
10std::string describe(TrafficLight light0) {11 if (light == Red) {if (light == Red)
10std::string describe(TrafficLight light) {11 if (light0 == Red) {12 return "stop";13 }action ← stop
23 std::string action→ stop = describe(light0);2425 std::cout << "light=" << light0 << std::endl;26 std::cout << "action=" << actionstop << std::endl;27 return 0;28}outputlight=0 action=stop
light ← 1
20int main() {21 TrafficLight light→ 1 = Yellow;2223 std::string action = describe(light1);std::string describe(TrafficLight light)
10std::string describe(TrafficLight light1) {11 if (light == Red) {if (light == Yellow)
13}14if (light1 == Yellow) {15 return "slow";16}action ← slow
23 std::string action→ slow = describe(light1);2425 std::cout << "light=" << light1 << std::endl;26 std::cout << "action=" << actionslow << std::endl;27 return 0;28}outputlight=1 action=slow