Control Flow
Mojo supports if/else, for, and while with Python-like syntax. The key difference: the compiler can analyze loop bounds and branch patterns to optimize execution. Predictable control flow enables vectorization and loop unrolling.
Code
fn main():
# Conditionals
var x: Int = 10
if x > 5:
print("greater")
elif x == 5:
print("equal")
else:
print("less")
# For loop with range
for i in range(5):
print(i)
# While loop
var count: Int = 0
while count < 3:
print(count)
count += 1
Loop Structure Impact
The compiler can optimize loops with known bounds. A for i in range(N) with constant N can be unrolled. A while loop with a dynamic condition cannot:
fn sum_fixed() -> Int:
var total: Int = 0
for i in range(1000): # compiler knows: 1000 iterations
total += i
return total
Constraint
Write a loop that sums integers from 0 to N. First use for i in range(N), then rewrite it as a while loop. Both should produce the same result.
Why It Matters
Branch prediction failures cost 10-20 CPU cycles each. Loops with predictable bounds let the compiler unroll iterations and eliminate branch checks. This is the foundation for SIMD vectorization in Phase 3 — the compiler needs to know loop trip counts to generate vector instructions.