C++ Academy · Lesson

Branching: if-else, ternary, switch-case

Choose between if-else chains, ternary expressions, and switch statements for clear branching.

Lesson 1 of 413 steps

Branching: if-else, ternary, switch-case is a free C++ Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

The if Statement

The basic conditional. The body executes when the condition is true. Curly braces are optional for a single statement but always recommended.

int score = 85;
if (score >= 60) {
    std::cout << "Pass\n";
}

if-else Chains

Test alternatives with else if and a final else. The first true branch runs.

if (score >= 90) std::cout << "A";
else if (score >= 80) std::cout << "B";
else if (score >= 70) std::cout << "C";
else std::cout << "F";

Boolean Conditions

Any expression convertible to bool works. Pointers test as false when null, and integers as false when zero. Be explicit for clarity.

Initializing in the if (C++17)

C++17 lets you declare a variable inside the if. The variable is scoped to the if-else body.

if (auto it = map.find(key); it != map.end()) {
    std::cout << it->second;
}

The Ternary Operator

condition ? a : b returns one of two values. Great for simple choices, terrible for nested logic.

int max = (a > b) ? a : b;
std::string msg = (n == 1) ? "item" : "items";

Nested Ternaries: Avoid

Nested ternaries are hard to read. Use if-else or refactor into a helper function instead.

// Hard to read
auto label = (n < 0) ? "neg" : (n == 0) ? "zero" : "pos";

// Clearer
std::string label;
if (n < 0) label = "neg";
else if (n == 0) label = "zero";
else label = "pos";

The switch Statement

Compare one value against several constants. Each branch needs break to avoid falling through to the next case.

switch (day) {
    case 1: std::cout << "Mon"; break;
    case 2: std::cout << "Tue"; break;
    default: std::cout << "?";  break;
}

Intentional Fallthrough

Group multiple cases that share code. C++17 added [[fallthrough]] as a marker for the compiler.

switch (c) {
    case 'a': case 'e': case 'i': case 'o': case 'u':
        std::cout << "vowel"; break;
    default:
        std::cout << "consonant";
}

switch Constraints

switch works only on integer and enum types. For strings, use if-else or a hash map.

Initializer in switch (C++17)

Similar to if, you can declare a variable inside the switch header.

switch (auto value = compute(); value) {
    case 0: ...
    default: ...
}

Pattern: Lookup Map

For string-keyed branches, a std::unordered_map can be cleaner than an if-else chain.

std::unordered_map<std::string, std::function<void()>> commands = {
    {"start", []{ start(); }},
    {"stop",  []{ stop();  }}
};
if (auto it = commands.find(cmd); it != commands.end())
    it->second();

Quick Check

What happens if a case in a switch lacks a break and the next case is non-empty?

Recap

Use if-else for general branching, the ternary operator for short value choices, and switch when comparing one value against many integer constants. C++17 init-statements clean up scoping.

Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Branching: if-else, ternary, switch-case” lesson free?

Yes — any 3 lessons of the C++ Academy learning path, including “Branching: if-else, ternary, switch-case”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

What will I learn in “Branching: if-else, ternary, switch-case”?

Choose between if-else chains, ternary expressions, and switch statements for clear branching. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Branching: if-else, ternary, switch-case” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Branching: if-else, ternary, switch-case
  2. Loop Patterns: for, while, do-while
  3. Range-Based for Loop with Containers
  4. Early Returns break continue and goto
← Back to C++ Academy