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 0 unless 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 enum called Day to represent the days of the week.
- The switch statement checks the value of today and executes the corresponding case block.
- Since today is set to Friday, 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 enum called Weather with explicit values for each weather type.
- The user inputs a number (1–4), which is cast to the Weather type using static_cast.
- static_cast is 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 switch statement uses the Weather value 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:
User Input is an Integer:
- When the user enters a number (e.g., 1, 2, 3, or 4), it is stored as an integer (int).
- However, the program expects a value of type Weather (which is an enum).
enum Values are Not Directly Compatible with Integers:
- Even though enum values are internally represented as integers, the compiler treats them as a distinct type.
- You cannot directly assign an integer to an enum variable without an explicit cast.
static_cast Ensures Safe Conversion:
- static_cast tells the compiler to treat the integer as a Weather type.
- 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 (the enum we 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 break statement in switch cases to avoid unintended fall-through execution.
- Use the default case as a fallback for unhandled cases.
- Enumerators in enum can be assigned custom values.
- Use static_cast to safely convert integers to enum values when required.
'C++ Beginner' 카테고리의 다른 글
cpp_019: Writing to Files with ofstream in C++ (0) | 2025.04.05 |
---|---|
cpp_019: Basics of Functions, Methods, Static Methods, and Constructors in C++ (0) | 2025.04.05 |
Cpp_017: Range-Based For Loops in C++ (0) | 2025.04.05 |
cpp_016: Comparing C-Style Arrays, std::array, and std::vector in C++ (0) | 2025.04.05 |
cpp_015: STL Array in C++ (0) | 2025.03.10 |