All lessons
LESSON 13/53Making Decisions
switch and ? :
GOALWrite a clean choice when one value is compared against many.

When one variable is compared against many exact values, a chain of else if gets long. switch is made for exactly that.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int day = 7;
switch (day) {
case 6:
case 7:
cout << "Weekend" << endl;
break;
case 1:
cout << "Monday again" << endl;
break;
default:
cout << "School day" << endl;
}
int age = 20;
cout << (age >= 18 ? "adult" : "child") << endl;
return 0;
}> what you see
Weekend adult
//LINE BY LINE
Watch it run
n = 1. The switch matches n against each case, looking for the one that fits.
When to reach for switch
- Good fit: one variable compared against many exact values (a menu, a day number, a letter grade).
- Poor fit: ranges (
score > 90), decimals, or comparing strings.
The ternary operator ? :
When there are only two outcomes and both are short, they fit on one line.
string label = (age >= 18) ? "adult" : "child";
// ижил утгатай:
string label2;
if (age >= 18) label2 = "adult";
else label2 = "child";Do not nest ternaries. Past two outcomes, if/else if reads far better.