Title here
Summary here
Here’s an example of how to use switch statements to handle multiple conditions across different branches.
#include <iostream>
#include <ctime>
int main() {
// Basic switch statement
int i = 2;
std::cout << "Write " << i << " as ";
switch (i) {
case 1:
std::cout << "one" << std::endl;
break;
case 2:
std::cout << "two" << std::endl;
break;
case 3:
std::cout << "three" << std::endl;
break;
}
// Switch with multiple expressions in the same case and default case
std::time_t now = std::time(0);
std::tm *ltm = std::localtime(&now);
switch (ltm->tm_wday) {
case 0: // Sunday
case 6: // Saturday
std::cout << "It's the weekend" << std::endl;
break;
default:
std::cout << "It's a weekday" << std::endl;
break;
}
// Switch without an expression to mimic if-else logic
int hour = ltm->tm_hour;
switch (true) {
case true:
if (hour < 12) {
std::cout << "It's before noon" << std::endl;
} else {
std::cout << "It's after noon" << std::endl;
}
break;
}
// Type switch example (using templates and function overloading in C++)
auto whatAmI = [](auto i) {
if constexpr (std::is_same_v<decltype(i), bool>) {
std::cout << "I'm a bool" << std::endl;
} else if constexpr (std::is_same_v<decltype(i), int>) {
std::cout << "I'm an int" << std::endl;
} else {
std::cout << "Don't know type " << typeid(i).name() << std::endl;
}
};
whatAmI(true);
whatAmI(1);
whatAmI("hey");
return 0;
}
To run the program, ensure you have a C++ compiler like g++
installed. Save the code to a file named switch.cpp
, compile it, and run the resulting executable:
$ g++ -o switch_example switch.cpp
$ ./switch_example
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type PKc
In this example, the C++ code demonstrates the use of switch statements with integral values, multiple case expressions, default cases, and emulating type switching with function templates. Note that C++ doesn’t have a built-in type switch, but we can achieve similar behavior using templates and function overloading.