cpp_018: Switch and Enum in C++
Switch statements and enums are powerful tools in C++ that help you write clean, efficient, and readable decision-making logic. In this tutorial, we’ll explore their syntax, functionality, and practical examples, followed by problems and solutions to reinforce your understanding.
1. Switch Statement
The switch statement allows you to test a variable or expression against multiple cases and execute the corresponding block of code.
Syntax:
switch (expression) {
case constant1:
// Code block 1
break;
case constant2:
// Code block 2
break;
default:
// Default code block
}expression: The variable or value being tested.case constant: Matches specific values of the expression.break: Terminates the switch case to prevent "fall-through" execution.default: Executes if none of the cases match.
2. Enum (Enumeration)
An enum is a user-defined data type that assigns names to integral constants, making your code more readable and maintainable.
Syntax:
enum EnumName {
constant1,
constant2,
constant3,
// ...
};- Enumerators are automatically assigned integer values starting from
0unless explicitly specified.
3. Example 1: Simple Switch with Enum
Let’s create a simple program that uses a switch statement with an enum to represent days of the week.
#include <iostream>
using namespace std;
enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
int main() {
Day today = Friday;
switch (today) {
case Monday:
cout << "It's Monday. Back to work!" << endl;
break;
case Friday:
cout << "It's Friday. The weekend is near!" << endl;
break;
case Sunday:
cout << "It's Sunday. Relax and recharge!" << endl;
break;
default:
cout << "It's a regular weekday." << endl;
}
return 0;
}Output:
It's Friday. The weekend is near!Explanation:
- We define an
enumcalledDayto represent the days of the week. - The
switchstatement checks the value oftodayand executes the corresponding case block. - Since
todayis set toFriday, the program prints the message for Friday.
4. Example 2: Scenario with Explicit Enum Values
In this example, we’ll use an enum with explicitly assigned values and a switch statement to suggest activities based on the weather.
#include <iostream>
using namespace std;
// Define an enum called Weather with explicit integer values for each weather type
enum Weather { Sunny = 1, Cloudy = 2, Rainy = 3, Snowy = 4 };
void suggestActivity(Weather w) {
switch (w) {
case Sunny:
cout << "It's sunny! Go for a walk or a picnic." << endl;
break;
case Cloudy:
cout << "It's cloudy. A perfect day for indoor activities." << endl;
break;
case Rainy:
cout << "It's rainy. Stay indoors and read a book." << endl;
break;
case Snowy:
cout << "It's snowy. Time for some skiing or snowball fights!" << endl;
break;
default:
cout << "Invalid weather type!" << endl;
}
}
int main() {
// Declare a variable of type Weather to store the current weather
Weather currentWeather;
// Declare an integer variable to store the user's input
int input;
// Ask the user to enter a number representing the weather type
cout << "Enter the weather type (1: Sunny, 2: Cloudy, 3: Rainy, 4: Snowy): ";
cin >> input; // Store the user's input in the variable 'input'
// Convert the integer input to the Weather enum type using static_cast
currentWeather = static_cast<Weather>(input);
// Call the suggestActivity function and pass the currentWeather as an argument
suggestActivity(currentWeather);
return 0; // End the program
}Input/Output:
Enter the weather type (1: Sunny, 2: Cloudy, 3: Rainy, 4: Snowy): 3
It's rainy. Stay indoors and read a book.Explanation:
- We define an
enumcalledWeatherwith explicit values for each weather type. - The user inputs a number (1–4), which is cast to the
Weathertype usingstatic_cast. static_castis a type of type casting in C++. It is used to explicitly convert one data type to another. It is a compile-time cast, meaning the conversion is checked at compile time, and it is generally considered safe for well-defined conversions.- The
switchstatement uses theWeathervalue to suggest an activity.
Why Do We Need static_cast?
In the context of the program, we use static_cast to convert an integer (entered by the user) into an enum value. Here’s why this is necessary:
Get CodeAddict’s stories in your inbox
Join Medium for free to get updates from this writer.
User Input is an Integer:
- When the user enters a number (e.g.,
1,2,3, or4), it is stored as an integer (int). - However, the program expects a value of type
Weather(which is anenum).
enum Values are Not Directly Compatible with Integers:
- Even though
enumvalues are internally represented as integers, the compiler treats them as a distinct type. - You cannot directly assign an integer to an
enumvariable without an explicit cast.
static_cast Ensures Safe Conversion:
static_casttells the compiler to treat the integer as aWeathertype.- This ensures that the conversion is valid and prevents potential errors.
How Does static_cast Work?
The syntax for static_cast is:
static_cast<NewType>(expression)NewType: The type you want to convert the expression to.expression: The value or variable you want to convert.
In the program:
currentWeather = static_cast<Weather>(input);Weather: The target type (theenumwe defined).input: The integer entered by the user.
This line converts the integer input into a Weather type and assigns it to the variable currentWeather.
5. Key Points to Remember
- Always use the
breakstatement inswitchcases to avoid unintended fall-through execution. - Use the
defaultcase as a fallback for unhandled cases. - Enumerators in
enumcan be assigned custom values. - Use
static_castto safely convert integers toenumvalues when required.







