Sisu
W0011

while condition that nothing in the loop changes

Warning

Built from the repository at commit a8614dc.

A while whose condition reads local variables that nothing in the loop changes is a warning, and the program still builds. Parameters, self and the names a pattern binds are locals too. The condition can hold literals, None, locals, operators, comparisons, ==, !=, is, an index and the built-in .len(). A call or a field in the condition means no warning, because it can see a change that the loop makes through an object. An == or != on a value that holds a class also means no warning, unless the other side is None. A condition with no local, such as 1 < 2 or a const, does not warn. A break, continue, return, panic or todo anywhere in the loop means no warning, and so does an error in the loop. There is no fix.

When the warning names a let mut that is never reassigned, W0002 does not warn about it. The fix of W0002 changes let mut to let, and that keeps the endless loop.

Why

No code outside the loop can change a local, so the condition has the same value on every pass. The loop either never runs or never ends.

Broken

fn count(n: i64) {
    let mut i = 0
    while i < n {
        print(i)
    }
}

fn main() {
    count(3)
}

What sisu says

warning[W0011]: the condition of this `while` never changes
 --> W0011.sisu:3:11
  |
3 |     while i < n {
  |           ^^^^^ nothing in the loop changes `i` or `n`
  |
  = help: change `i` in the loop or leave it with `break`; write `if` to run the body once, or `loop` to run it forever

sisu: 1 warning
sisu: for more on a code, run `sisu explain <code>`: W0011

Fixed

A loop that you switch off on purpose reads a const. A loop that must end changes its condition in the loop.

const RUNNING = false

fn count(n: i64) {
    while RUNNING {
        print(0)
    }
    let mut i = 0
    while i < n {
        print(i)
        i += 1
    }
}

fn main() {
    count(3)
}

Related

  • W0002: variable that is never reassigned.
  • W0009: while with the condition true.
  • W0010: function that calls itself on every path.