Lesson 42 of 45 · C++
Lesson 6: Control Flow – if, else, switch
Duration: 10 min
Lesson 42 of 45 · C++
Duration: 10 min
if, else, switch\n\nConditional statements let a program choose between alternative execution paths. if evaluates a boolean expression, optionally followed by else if and a final else. The switch statement jumps to a case label based on an integral or enumeration value.\n\n---\n\n## Example: if‑else and switch\ncpp\nint score = 85;\nif (score >= 90) {\n std::cout << \"Grade A\" << '\\n';\n} else if (score >= 80) {\n std::cout << \"Grade B\" << '\\n';\n} else {\n std::cout << \"Grade C or lower\" << '\\n';\n}\n\nenum class Color { Red, Green, Blue };\nColor c = Color::Green;\nswitch (c) {\n case Color::Red: std::cout << \"Red\\n\"; break;\n case Color::Green: std::cout << \"Green\\n\"; break;\n case Color::Blue: std::cout << \"Blue\\n\"; break;\n default: std::cout << \"Unknown\\n\"; break;\n}\n\n\n> Tip: With C++17 you can use if constexpr to conditionally compile branches based on compile‑time constants.\n\n---\n\n<Alert type="warning">switch does not support float or std::string directly. Use if‑else or a std::map for those cases.