Lesson 47 min read

Conditionals

Same traffic lights as C, but C++ added some quality-of-life upgrades

Traffic Lights You Already Know

Conditionals in C++ are like traffic lights β€” they control the flow of execution. Green means go, red means stop, yellow means... well, it depends. If you already know C's conditionals, you're 90% there. C++ keeps if, else, switch, and the ternary operator exactly as they are.

But C++ isn't content with just inheriting. It added C++17's if-with-initializer β€” a small but powerful upgrade that keeps your code cleaner. Let's walk through everything.

Classic if / else β€” Same as C

#include <iostream>
using namespace std;
int main() {
int temperature = 35;
if (temperature >= 30) {
cout << "It's hot! Stay hydrated." << endl;
} else if (temperature >= 20) {
cout << "Nice weather for a walk." << endl;
} else if (temperature >= 10) {
cout << "Grab a jacket." << endl;
} else {
cout << "Bundle up, it's freezing!" << endl;
}
// C++ bonus: bool comparisons are cleaner
bool isRaining = true;
if (isRaining) { // no need for == true
cout << "Bring an umbrella!" << endl;
}
return 0;
}
Output
It's hot! Stay hydrated.
Bring an umbrella!

The switch Statement

Switch is like a vending machine β€” you insert a value, and it jumps directly to the matching case. It's faster and cleaner than a long if-else chain when you're comparing a single variable against discrete values.

The rules are the same as C: don't forget break, and always include a default case.

switch Statement

#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday!" << endl;
break;
default:
cout << "Weekend!" << endl;
break;
}
// switch with char works too
char grade = 'B';
switch (grade) {
case 'A': cout << "Excellent!" << endl; break;
case 'B': cout << "Good job!" << endl; break;
case 'C': cout << "Passing." << endl; break;
default: cout << "Keep trying." << endl; break;
}
return 0;
}
Output
Wednesday
Good job!
Note: C++ switch still only works with integral types β€” int, char, enum, and similar. You cannot switch on strings! For string matching, use if-else chains or a std::map that maps strings to actions.

String Matching with map β€” The switch Alternative

Since switch won't work with strings, here's a clean pattern using std::map that avoids ugly if-else chains:

String "switch" Using a Map

#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> commandMap = {
{"start", 1},
{"stop", 2},
{"pause", 3}
};
string input = "stop";
auto it = commandMap.find(input);
if (it != commandMap.end()) {
switch (it->second) {
case 1: cout << "Starting..." << endl; break;
case 2: cout << "Stopping..." << endl; break;
case 3: cout << "Pausing..." << endl; break;
}
} else {
cout << "Unknown command: " << input << endl;
}
return 0;
}
Output
Stopping...

The Ternary Operator β€” One-Line Decisions

The ternary operator condition ? a : b is a compact if-else for simple choices. It's perfect for assignments and inline expressions β€” but don't nest them, or your code becomes an unreadable puzzle.

Ternary Operator

#include <iostream>
#include <string>
using namespace std;
int main() {
int score = 85;
// Simple ternary β€” great for one-line assignments
string result = (score >= 60) ? "Pass" : "Fail";
cout << "Result: " << result << endl;
// Inline in output
int items = 1;
cout << "You have " << items << " item" << (items == 1 ? "" : "s") << endl;
items = 5;
cout << "You have " << items << " item" << (items == 1 ? "" : "s") << endl;
// Finding the max of two numbers
int a = 42, b = 17;
int maxVal = (a > b) ? a : b;
cout << "Max: " << maxVal << endl;
return 0;
}
Output
Result: Pass
You have 1 item
You have 5 items
Max: 42

C++17: if with Initializer

This is the quality-of-life upgrade that makes C++ devs smile. Before C++17, if you needed to check a value from a function, you'd create a variable that leaks into the surrounding scope. Now you can declare and test in one statement, and the variable stays confined to the if block.

Think of it as putting on a pair of gloves, doing a job, and automatically taking them off β€” no mess left behind.

C++17 if with Initializer

#include <iostream>
#include <string>
#include <map>
using namespace std;
int getValue() { return 42; }
int main() {
// Before C++17 β€” variable leaks into outer scope
{
int val = getValue();
if (val > 0) {
cout << "Old style: val = " << val << endl;
}
// val is still alive here... polluting the scope
}
// C++17 β€” variable is scoped to the if block
if (auto val = getValue(); val > 0) {
cout << "C++17 style: val = " << val << endl;
}
// val doesn't exist here anymore β€” clean!
// Real-world example: map lookup
map<string, int> scores = {{"Alice", 95}, {"Bob", 87}};
if (auto it = scores.find("Alice"); it != scores.end()) {
cout << it->first << " scored " << it->second << endl;
} else {
cout << "Not found" << endl;
}
// 'it' is gone here β€” no leaking iterators
return 0;
}
Output
Old style: val = 42
C++17 style: val = 42
Alice scored 95
Challenge

Quick check

Can you use a std::string in a switch statement in C++?
← Input & OutputLoops β†’