> For the complete documentation index, see [llms.txt](https://nodejsdocs.gitbook.io/everthing-c++/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nodejsdocs.gitbook.io/everthing-c++/control-flow-branching-and-performance-in-c++.md).

# Control Flow, Branching & Performance in C++

This chapter dives into the heart of decision-making in C++ — **control flow**, including `if`, `switch`, and loop constructs — but through the lens of **low-level system performance**, **predictability**, and **hardware alignment**. You’ll learn not just the syntax, but how these decisions affect **CPU branch prediction**, **pipeline stalls**, and **cache locality**, critical in high-performance systems.

***

### 1. Conditional Statements

#### 1.1 `if`, `else if`, and `else`

```cpp
int x = 10;
if (x > 0) {
    std::cout << "Positive";
} else if (x < 0) {
    std::cout << "Negative";
} else {
    std::cout << "Zero";
}
```

#### Performance Tip:

* **Predictability Matters**: CPUs predict branches. Stable, predictable branches are fast.
* Convert unpredictable branches to arithmetic:

```cpp
// Instead of:
if (x > 0) sum += x; else sum -= x;

// Use:
sum += (x > 0 ? 1 : -1) * x;
```

***

### 2. Switch Statement

#### Syntax:

```cpp
switch (value) {
    case 1: std::cout << "One"; break;
    case 2: std::cout << "Two"; break;
    default: std::cout << "Other";
}
```

#### Best Practices:

* Always use `break` to avoid fallthrough (unless intentional).
* Use `enum class` instead of `int` for type safety.

#### Compiler Optimization:

* Modern compilers convert dense `switch` to jump tables.
* Sparse `case` values become chained `if` statements.

***

### 3. Loops and Iterations

#### 3.1 `for`, `while`, and `do-while`

```cpp
for (int i = 0; i < 10; ++i) {
    std::cout << i << " ";
}
```

#### 3.2 Range-Based `for`

```cpp
std::vector<int> vec = {1, 2, 3};
for (int x : vec) {
    std::cout << x;
}
```

#### 3.3 Loop Optimizations

* **Precompute Loop Invariants** outside the loop.
* Prefer **++i** over **i++** for iterators (avoids temp object).
* Reduce branching inside loops (use masking/arithmetic).

#### Branch Elimination:

```cpp
// Instead of
for (int i = 0; i < N; ++i)
    if (cond[i]) process(i);

// Use
for (int i = 0; i < N; ++i)
    process(i * cond[i]);
```

***

### 4. Goto and Labels (Rare but Used in Systems Code)

```cpp
void foo() {
    if (error) goto fail;
    // logic
fail:
    // cleanup
}
```

Used in **kernel-level**, **device drivers**, and **fast error unwinding**.

***

### 5. Branch Prediction Hints (Compiler Extensions)

```cpp
if (__builtin_expect(condition, 1)) {
    // Likely path
} else {
    // Unlikely path
}
```

#### Why It Matters

* Tells the compiler to optimize for the likely branch.
* Reduces **branch misprediction penalty**.

***

### 6. Pipeline Stalls and Branch Misprediction

Modern CPUs use **pipelining** to execute multiple instructions simultaneously. But control flow breaks this in subtle ways:

#### 6.1 What Is a Pipeline Stall?

* A stall happens when the CPU waits for the result of an earlier instruction (e.g., load from memory or branch resolution).
* Happens often in branches and mispredicted conditionals.

#### 6.2 Branch Misprediction

* CPUs speculatively execute based on prediction.
* A wrong guess causes all speculative results to be **discarded**, flushing the pipeline.
* Cost: **15–25 CPU cycles** (on modern x86 CPUs).

#### 6.3 Optimizing for Predictability

* Place likely branches first (`if (likely) { ... }`)
* Avoid deeply nested conditionals.
* Use arithmetic or masking when safe.

```cpp
// Unpredictable branch
if (rand() % 2 == 0) handle();

// Predictable replacement
handle(rand() % 2 * flag);
```

***

### 7. Tricky Control Flow Questions (with Sources)

#### Q1. Predict the Output

📚 *Source: StackOverflow Advanced Threads*

```cpp
int x = 5;
switch (x) {
    case 5:
    case 6:
        std::cout << "Hello";
    default:
        std::cout << "World";
}
```

🧠 **Answer:** `HelloWorld` — fallthrough occurs without `break`

***

#### Q2. Infinite Loop

📚 *Source: GeeksforGeeks Interview*

```cpp
int i = 0;
while (i++ < 5);
    std::cout << i;
```

🧠 **Answer:** `6` — the semicolon ends the loop early. `cout` executes once after the loop.

***

#### Q3. Masking for Conditional Execution

📚 *Inspired by Performance-Critical Systems*

```cpp
int a = 4, b = 6;
int max = a ^ ((a ^ b) & -(a < b));
std::cout << max;
```

🧠 **Answer:** `6` — this avoids branching entirely. Low-level trick to find max.

***

### 8. Summary Table

| Concept             | Optimization Tip                             |
| ------------------- | -------------------------------------------- |
| `if`/`else`         | Prefer predictability, reduce nesting        |
| `switch`            | Use `enum class`, dense ranges = fast jumps  |
| Loops               | Hoist invariants, use `++i`, minimize branch |
| `goto`              | Rare, use for error unwinding only           |
| Branch Prediction   | Use `__builtin_expect` where supported       |
| Conditional Masking | Replace `if` with arithmetic where needed    |
| Pipelining          | Avoid unpredictable branches                 |
| Misprediction       | Costs cycles, reorder to help CPU predict    |

***

Next up: **Functions, Inlining, and Stack Frame Behavior** — core to understanding performance tuning, call overhead, and recursion control.
