Switch Statements
Switch statements are useful in evaluating multiple conditions/cases within an evaluation.
In the following example we look at using the switch statement for case evaluation. First we create an enum class for Weather types. We then create a switch statement with evaluations for different cases.
#include <cstdio>
enum class Weather {
Snowy,
Sunny,
Cloudy,
Rainy,
Stormy
};
int main() {
Weather weather_today = Weather::Stormy;
switch (weather_today) {
case (Weather::Snowy) : {
printf("Better get that Snow Jacket ");
} break;
case (Weather::Sunny): {
printf("Beautiful Day out today! \n");
} break;
case (Weather::Cloudy) : {
printf("It might rain today carry an Umbrella! \n");
} break;
case (Weather::Rainy): {
printf("You are definitely going to be socking wet out there! \n");
} break;
case (Weather::Stormy): {
printf("Maybe you stay indoors instead! \n");
} break;
default: {
printf("You might be in trouble if you don't know the Weather \n");
} break;
}
}
Below, I compile the switch.cpp file above and run the executable.
$ g++ switch.cpp -std=c++17 -o switch
$ ./switch
Maybe you stay indoors instead!