Conditionals
Conditionals choose which statements run. if / else tests a boolean condition. switch matches an integer or enumeration against a list of constant cases. Both decide control flow; they do not produce a value unless you use C++20's if with an initialiser or assign inside the branches.
Detailed Explanation
You are looking at an HTTP status. 200 means success, 404 means missing, everything else is a generic failure. That is a three-way decision. C++ gives you if for arbitrary conditions and switch for a discrete set of constant labels.
if (cond) statement runs the statement when cond converts to true. An optional else covers the other path. The condition is converted to bool. For class types that means operator bool or a conversion; for pointers it means "not null"; for numbers it means "not zero". Write the comparison you mean (count > 0) rather than relying on implicit conversion, except for the idiomatic if (ptr) null check.
C++17 added an initialiser: if (auto it = m.find(key); it != m.end()). The initialiser's names are in scope for both the if and the else, and they die at the end of the whole construct. That keeps lookup variables from leaking into the rest of the function.
switch (expr) evaluates expr once, then jumps to the case whose constant matches. expr must be an integral type, an enumeration, or a class with a conversion to one of those. Each case label must be a constant expression. default is the fallback. Execution does not stop at the end of a case. It falls through into the next case unless you break, return, goto a later label, or throw. That is inherited from C. It is useful when two cases share a tail. It is a defect when you forget break.
C++17 also added if constexpr (cond). The condition must be a constant expression. The discarded branch is not instantiated. That is how a template can contain a t.push_back(x) for vectors and a t.insert(x) for sets in the same function without either type seeing the other's API. It is not a faster if. It is a compile-time branch.
The ternary operator cond ? a : b is an expression. It produces a value, so both branches must have a common type. Use it for short choices in an initialiser (const char* label = ok ? "yes" : "no"). Do not nest it into a decision tree; that is what if is for.
switch on a scoped enumeration (enum class) does not silently match an int. You write Status::Ok. Compilers can warn about missing enumerators when there is no default, which is a reason to omit default if the enum is closed and you want a warning when someone adds a case.
Cost: a well-predicted if is a few instructions. A switch with dense cases often becomes a jump table; a sparse one becomes a binary search or a chain of compares. You do not pick between them for speed first. You pick switch when the condition is "which of these constants" and if when it is "is this true".
Code Examples
#include <iostream>
#include <string>
int main() {
int status = 404;
if (status == 200) {
std::cout << "ok\n";
} else if (status == 404) {
std::cout << "missing\n"; // prints: missing
} else {
std::cout << "error\n";
}
std::string body = (status == 200) ? "ok" : "fail";
std::cout << body << '\n'; // prints: fail
}#include <iostream>
enum class Status { Ok, NotFound, Error };
void handle(Status s) {
switch (s) {
case Status::Ok:
std::cout << "ok\n";
break;
case Status::NotFound:
std::cout << "missing\n";
break;
case Status::Error:
std::cout << "error\n";
break;
}
}
int main() {
handle(Status::NotFound); // prints: missing
}#include <map>
#include <string>
#include <iostream>
int main() {
std::map<std::string, int> ages{{"ada", 36}};
if (auto it = ages.find("ada"); it != ages.end()) {
std::cout << it->second << '\n'; // prints: 36
}
}Common Gotchas
`switch` falls through
without `break`, case `200` will run case `404`'s statements too. If you fall through on purpose, write `[[fallthrough]];` so reviewers and compilers know.
`if constexpr` requires a compile-time condition
`if constexpr (n > 0)` fails when `n` is a runtime `int`. Use a plain `if`.
Assignment in a condition
`if (x = y)` compiles and is almost never what you meant. Enable `-Wparentheses` or write `if ((x = y))` only when the assignment is the point.
`switch` cannot match strings
there is no built-in `switch` on `std::string`. Use `if`/`else`, a map of handlers, or compare hashes you have validated.