C++ — Selecting a branch with if and else
In C++, an if and else if chain tests conditions in order. The first true branch runs, and an optional else handles everything left over.
A simple example
Follow one branch
- Start with n is 2
- Do this Is n positive?
- Result yes
#include <iostream>
int main() {
int n = 2;
if (n > 0) {
std::cout << ("yes") << '\n';
} else {
std::cout << ("no") << '\n';
}
}
yes
Classify a stock level
Every reachable branch assigns the string before it is printed. For a small mutually exclusive set of ranges, an ordered if/else chain makes boundary values easy to check.
A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.
Run the example
C++17. Run these commands from the directory containing the example. Use a Unix-style shell.
c++ -std=c++17 lesson.cpp -o lesson
./lesson
#include <iostream>
#include <string>
int main() {
int stock = 3;
std::string status;
if (stock == 0) {
status = "sold out";
} else if (stock <= 5) {
status = "order soon";
} else {
status = "in stock";
}
std::cout << status << '\n';
return 0;
}
order soon
The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.
Try it yourself
Try the boundary values 0, 5, and 6.
Check your answer
They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.