Learn++ Lesson 42: Enumerated Types in C++ Programming
Enumerated types define a small set of named constants. In modern C++, enum class makes related values clear and keeps comparisons type-safe.
Define and use an enum class
#include <iostream>
enum class Color {Red, Green, Blue};
int main() {
Color c = Color::Red;
if (c == Color::Red) {
std::cout << "It's red!";
}
return 0;
}
Output:
It's red!
The Color type groups the named values. The variable c stores Color::Red, and the condition checks that value before printing the message.
Why enumerated types matter
- They make related values readable and self-documenting.
- They reduce the need for unexplained numeric constants.
enum classkeeps the values scoped and strongly typed.
What you practice in Learn++
- Defining an
enum class. - Using a scoped enumerator such as
Color::Red. - Comparing an enum value safely in an
ifstatement.
Today's challenge
Fill in the missing scoped type and enumerator so the program prints It's red!:
#include <iostream>
enum class Color {Red, Green, Blue};
int main() {
Color c = Color::Red;
if (c == _____::___) {
std::cout << "It's red!";
}
return 0;
}
The unique answer is Color::Red: Color is the enum type and Red is the matching enumerator.