C++ If Else and Switch
C++ if else statements and switch statements let your program choose what to do based on conditions. They work like in C, with a few modern extras.
if, else if and else
#include <iostream>
int main() {
int hour = 15;
if (hour < 12) {
std::cout << "Good morning\n";
} else if (hour < 18) {
std::cout << "Good afternoon\n";
} else {
std::cout << "Good evening\n";
}
}Good afternoon
Ternary Operator
#include <iostream>
#include <string>
int main() {
int stock = 0;
std::string status = stock > 0 ? "In stock" : "Sold out";
std::cout << status << '\n';
}Sold out
if with an Initializer
Since C++17 you can declare a variable inside the if itself, keeping its scope small.
#include <iostream>
#include <string>
int main() {
std::string email = "naeem@example.com";
if (auto at = email.find('@'); at != std::string::npos) {
std::cout << "Domain: " << email.substr(at + 1) << '\n';
}
}Domain: example.com
The C++ Switch Statement
switch compares an integer, char or enum against constant cases. Remember break, or execution falls through to the next case. Mark intentional fall-through with [[fallthrough]].
#include <iostream>
int main() {
char op = '*';
int a = 6, b = 7;
switch (op) {
case '+': std::cout << a + b << '\n'; break;
case '-': std::cout << a - b << '\n'; break;
case '*': std::cout << a * b << '\n'; break;
default: std::cout << "Unknown operator\n";
}
}42
Frequently asked questions
Can I use strings in a C++ switch?
No. switch only works with integral types and enums. Use if else with == for std::string, or map strings to values with std::unordered_map.
What is [[fallthrough]] in C++?
It is an attribute that tells the compiler and readers that falling into the next case is intentional, silencing the warning.
When should I use switch instead of if else?
Use switch when comparing a single integer, char or enum against many fixed values. Use if else for ranges and complex conditions.