Solidity theorytheory 0/50 · 0%
Fundamentals · easy

11. Control flow

if, for, while, break and continue in a gas-metered world.

Control flow looks like C, but every iteration costs gas, so loops must be bounded by something the caller controls or by a constant.

for (uint256 i; i < xs.length; ++i) {
    if (xs[i] == 0) continue;
    total += xs[i];
}

Prefer `++i` over `i++` and cache `xs.length` in a local for a small saving on hot loops.

Check your understanding

  1. 1. Why must loops be bounded?

  2. 2. Which is marginally cheaper?

  3. 3. What does `continue` do?