C++ If...Else and Switch
Conditions let your program decide what to do based on the data it has.
if and else
Example
#include <iostream>
using namespace std;
int main() {
int balance = 1500;
int fare = 250;
if (balance >= fare) {
balance -= fare;
cout << "Ride booked. Balance left: " << balance << "\n";
} else {
cout << "Please top up your wallet\n";
}
return 0;
}Ride booked. Balance left: 1250
else if
Check conditions one after another. Only the first true block runs:
Example
#include <iostream>
using namespace std;
int main() {
int hour = 15;
if (hour < 12) {
cout << "Good morning\n";
} else if (hour < 17) {
cout << "Good afternoon\n";
} else {
cout << "Good evening\n";
}
return 0;
}Good afternoon
Nested if
You can put an if inside another if:
Example
int age = 20;
bool hasLicense = false;
if (age >= 18) {
if (hasLicense) {
cout << "You can drive\n";
} else {
cout << "Get a license first\n";
}
}Get a license first
Deep nesting is hard to read. Often you can join the conditions with && instead, like if (age >= 18 && hasLicense).
The Ternary Operator
condition ? a : b gives a when true and b when false:
Example
int marks = 45;
string result = (marks >= 50) ? "Pass" : "Fail";
cout << result << "\n";Fail
switch
switch compares one value (an integer, char or enum) against fixed cases:
Example
#include <iostream>
using namespace std;
int main() {
int option = 2;
switch (option) {
case 1:
cout << "Check balance\n";
break;
case 2:
cout << "Withdraw cash\n";
break;
case 3:
cout << "Change PIN\n";
break;
default:
cout << "Invalid option\n";
}
return 0;
}Withdraw cash
| Keyword | Meaning |
|---|---|
case | One value to match |
break | Stops the switch here |
default | Runs when no case matches |
switch does not work with string. For text, use if and else if instead.
if with an Initializer (C++17)
Modern C++ lets you create a variable that only lives inside the if:
Example
if (int stock = 3; stock < 5) {
cout << "Low stock: " << stock << "\n";
}Low stock: 3
Exercise
Exercise
What happens if you leave out break at the end of a case in a C++ switch?
