Module 2 · Lesson 3 of 36/26 in the course~10 min
Module lessons (3/3)
Education switch
Lesson preview5 hands-on exercises readyCourse C++ · Module 2 — Flow Control
Manage multiple branchings in an orderly manner based on constant integer or char values.
What you'll learn in this lesson
- Replace long scales of
if / else ifon discrete values with a clear, readableswitchblock. - Always manage
break(anddefault) avoiding involuntary fall-through between onecaseand the next. - Matching
switchto strongly typedenum classin modern C++.
Overview
When you need to compare a single discrete expression (int, char, bool, or enum) against many known constants at compile time, switch expresses the intent better than ten else if in a row and allows the compiler to generate a jump table in O(1) time.
Each case requires a constant label at compile time, while default captures all other values:
Sections covered in this lesson
- 11. Structure
switch / case / break / default - 22. Fall-Through: Accidental Bug or Intentional Bundling
- 33. Allowed Types and
enum class(Scoped Enum) - 44. Local Variables Inside a
case(Graffe{}) - 5Practical exercises
- 6Check for understanding
Pro Lesson · Module 2 — Flow Control
Unlock "Education switch" and the full Course C++ curriculum
Manage multiple branchings in an orderly manner based on constant integer or char values.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course C++ plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.