Control Statements
In C++, control statements are the building blocks that dictate program execution flow. They empower us to make decisions, handle edge cases, and build responsive applications. This section dives into two essential constructs: if / else and switch. These tools form the backbone of conditional logic in your codebase.
if / else
The if / else statement is C++’s most versatile conditional construct. It evaluates a boolean expression and executes one of two code blocks based on whether the expression is true or false. This structure is indispensable for handling real-world scenarios where decisions depend on runtime conditions.
Here’s the core syntax:
<code class="language-cpp">if (condition) {
<p> // Code to execute if condition is true</p>
<p>} else {</p>
<p> // Code to execute if condition is false</p>
<p>}</code>
Let’s walk through practical examples that demonstrate real-world applications:
Example 1: Basic positive/negative check
<code class="language-cpp">#include <iostream>
<p>int main() {</p>
<p> int num = -5;</p>
<p> if (num > 0) {</p>
<p> std::cout << "Positive number";</p>
<p> } else {</p>
<p> std::cout << "Non-positive number";</p>
<p> }</p>
<p> return 0;</p>
<p>}</code>
Output: Non-positive number
Example 2: Grade conversion with else-if chain
<code class="language-cpp">#include <iostream>
<p>int main() {</p>
<p> int score = 78;</p>
<p> if (score >= 90) {</p>
<p> std::cout << "A";</p>
<p> } else if (score >= 80) {</p>
<p> std::cout << "B";</p>
<p> } else if (score >= 70) {</p>
<p> std::cout << "C";</p>
<p> } else {</p>
<p> std::cout << "D";</p>
<p> }</p>
<p> return 0;</p>
<p>}</code>
Output: C
Example 3: Nested conditionals for multi-criteria validation
<code class="language-cpp">#include <iostream>
<p>int main() {</p>
<p> int age = 22;</p>
<p> int height = 172;</p>
<p> if (age >= 18) {</p>
<p> if (height >= 170) {</p>
<p> std::cout << "Adult and tall enough";</p>
<p> } else {</p>
<p> std::cout << "Adult but not tall enough";</p>
<p> }</p>
<p> } else {</p>
<p> std::cout << "Not an adult";</p>
<p> }</p>
<p> return 0;</p>
<p>}</code>
Output: Adult and tall enough
Critical best practices:
- Always use braces
{}for blocks—even single-line blocks—to prevent ambiguity else ifchains are evaluated sequentially; the firsttruecondition triggers execution- Avoid deep nesting by restructuring logic (e.g., using
else ifchains over multipleifstatements) - Never omit
breakinswitch(we’ll cover this in the next section)
The if / else construct is your go-to for flexible decision-making. Master it, and you’ll write code that adapts to complex real-world scenarios. 🚀
switch
The switch statement provides an elegant alternative to chained if / else when comparing a single expression against multiple discrete values. It’s especially efficient for handling integer, enum, or character-based cases.
Here’s the standard syntax:
<code class="language-cpp">switch (expression) {
<p> case value1:</p>
<p> // Code for value1</p>
<p> break;</p>
<p> case value2:</p>
<p> // Code for value2</p>
<p> break;</p>
<p> ...</p>
<p> default:</p>
<p> // Code for no matches</p>
<p>}</code>
Example 1: Simple grade-to-score conversion
<code class="language-cpp">#include <iostream>
<p>int main() {</p>
<p> char grade = 'B';</p>
<p> int score = 0;</p>
<p> switch (grade) {</p>
<p> case 'A':</p>
<p> score = 90;</p>
<p> break;</p>
<p> case 'B':</p>
<p> score = 80;</p>
<p> break;</p>
<p> case 'C':</p>
<p> score = 70;</p>
<p> break;</p>
<p> default:</p>
<p> score = 0;</p>
<p> }</p>
<p> std::cout << "Score: " << score;</p>
<p> return 0;</p>
<p>}</code>
Output: Score: 80
Example 2: Day-of-week mapping
<code class="language-cpp">#include <iostream>
<p>int main() {</p>
<p> int day = 3;</p>
<p> std::string dayName;</p>
<p> switch (day) {</p>
<p> case 1:</p>
<p> dayName = "Monday";</p>
<p> break;</p>
<p> case 2:</p>
<p> dayName = "Tuesday";</p>
<p> break;</p>
<p> case 3:</p>
<p> dayName = "Wednesday";</p>
<p> break;</p>
<p> default:</p>
<p> dayName = "Other";</p>
<p> }</p>
<p> std::cout << "Day: " << dayName;</p>
<p> return 0;</p>
<p>}</code>
Output: Day: Wednesday
Key behaviors to understand:
- The
expressionmust be an integer, enum, or character (C++17+ supportsstd::stringvia explicit conversion) - Always include
breakafter eachcaseto prevent “fall-through” (execution continuing to the next case) - The
defaultcase executes when nocasematches - No
break= fall-through (a common pitfall):
<code class="language-cpp"> switch (day) {</p>
<p> case 1: std::cout << "Mon"; // No break</p>
<p> case 2: std::cout << "Tue"; // This runs too!</p>
<p> }</code>
Output: Monto
if / else vs. switch: When to use which
| Feature | if / else |
switch |
|---|---|---|
| Best use case | Complex conditions, string comparisons | Discrete integer/enum/char values |
| Expression type | Any boolean expression | Integer, enum, or char (C++17+) |
| Case handling | One condition per block | Multiple discrete values with case labels |
| Readability | High for simple logic | Higher for value-based decisions |
| Common pitfalls | Deep nesting, complex boolean expressions | Fall-through without break |
Pro tip: Use switch for:
- Converting enums to strings
- Mapping discrete codes to actions
- Handling integer inputs with limited valid ranges
Avoid switch for:
- String comparisons (use
if / elseorstd::stringmethods) - Complex boolean logic (use
if / else)
Summary
You now have two powerful tools for conditional logic in C++:
if / else: For flexible, complex decision-makingswitch: For efficient handling of discrete values
Master these constructs by:
- Using braces for all blocks
- Adding
breakin everyswitchcase - Choosing
switchfor discrete values andif / elsefor complex conditions
These patterns ensure your code remains readable, maintainable, and robust. Remember: the right tool for the job makes your logic both efficient and intuitive. 🔁