3.09 Loop Stride Adjustments (i += 2) vs Internal Filtering & Branch Overhead
Executive Summary: Generating even-number sequences. We demonstrate why advancing the loop step size directly (i += 2) executes twice as fast as iterating every number and filtering with if (i % 2 == 0), eliminating half the loop iterations and 100% of branch conditions.
💻 1. Annotated Source Code
#include <iostream> using namespace std; int main() { int count = 0; while (count < 10) { if (count % 2 != 0) { count++; continue; } cout << count << endl; count++; } return 0; }
📐 2. Architecture & UML Class Model
<<compilation-unit>>
EvenFilterEngine
Filter Unit
Attributes / Data Members
-lowerBound : int32_t
-upperBound : int32_t
Operations / Methods
+printEvenRange(start: int, end: int) : void[i += 2 step]
📚 3. Core C++ Concepts Deep-Dive
1. Iteration Filtering vs Stride Adjustment
- Filtering (
i++withif (i%2 == 0)): Executes $N$ iterations and performs $N$ conditional tests. - Stride Adjustment (
i += 2): Executes $\frac{N}{2}$ iterations with 0 conditional tests!
⚡ 4. Embedded Systems & Hardware Reality
1. 50% Cycle Reduction
Adjusting the loop stride cuts instruction count in half, directly reducing CPU power consumption and thermal dissipation on battery-powered sensor nodes.
💡 5. Production-Ready Embedded Refactoring
Optimal stride-based iteration:
💡 Production-Ready Refactor
#include <cstdint> // Iterates only over even indices (50% fewer clock cycles!) void processEvenSensors(const uint16_t* data, size_t count) noexcept { for (size_t i = 0; i < count; i += 2) { // Direct processing with zero if-checks! } }
📝 Knowledge Verification Quiz
Test your understanding of the C++ concepts and embedded microcontroller trade-offs covered in this guide. Click any option for instant feedback.
Q1. Why is 'for (int i=0; i<100; i+=2)' strictly more efficient than 'for (int i=0; i<100; i++) if (i%2==0)'?
Detailed Explanation:
Stepping by 2 executes 50 iterations instead of 100 and removes the
if branch test entirely.
Q2. How does reducing loop iteration count benefit battery-powered embedded devices?
Detailed Explanation:
In energy-harvesting and battery systems ('race-to-sleep' strategy), finishing processing in fewer clock cycles allows the CPU to enter low-power sleep mode sooner.
Q3. What is the initial value of 'i' to iterate over only odd numbers with 'i += 2'?
Detailed Explanation:
Starting at 1 and stepping by 2 visits 1, 3, 5, 7... (all odd integers).
Q4. What assembly instruction increments a register by 2 on ARM Cortex-M?
Detailed Explanation:
ADDS r0, r0, #2 adds 2 to register r0 in a single clock cycle.