C++
Module 7: Control StatementsBeginner40 min read

Decision Making: if-else, switch & Enum Switching

Write clean conditional logic using if, if-else, else-if ladders, switch statements, C++17 init-statements, and enum class.

Key Takeaways & Core Concepts
  • `if / else if / else`: Evaluates boolean expressions sequentially.
  • C++17 Init-Statement: if (auto val = compute(); val > 0) { ... } keeps val scoped strictly to the conditional.
  • `switch`: Branches on integral or enum values using compiler jump tables (often O(1)). Always include break; unless using C++17 [[fallthrough]];.

1. Conditional Branching

  • `if / else if / else`: Evaluates boolean expressions sequentially.
  • C++17 Init-Statement: if (auto val = compute(); val > 0) { ... } keeps val scoped strictly to the conditional.
  • `switch`: Branches on integral or enum values using compiler jump tables (often O(1)). Always include break; unless using C++17 [[fallthrough]];.
1. C++17 Init-If & Enum Class Switch
1#include <iostream>
2enum class Tier { Free, Pro, Enterprise };
3
4int main() {
5 if (Tier t = Tier::Pro; t == Tier::Pro) {
6 std::cout << "Pro Tier Active\n";
7 }
8 return 0;
9}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: Demonstrates C++17 init-statement inside `if` with scoped `enum class`.

2. `if-else` vs `switch`

Use switch for discrete constant cases (enum class, menu choices); use if-else for ranges (score >= 90) or complex boolean logic.

Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)