Section 3.24

Loop invariant

Definition

A loop invariant is a condition on a program’s variables that holds every time execution reaches a loop’s test: before the first iteration and after each one. It is proved by induction: the condition holds when the loop is entered, and one run of the body, started where both the condition and the loop test hold, ends where the condition holds again. When the loop exits, the invariant together with the failed test gives the loop’s result. An invariant says nothing about whether the loop ever exits.

The idea

A loop can run any number of times, so its iterations cannot be checked one by one. Take i = 0; s = 0; while (i < n) { s = s + a[i]; i = i + 1; }, which must add up the n elements of the array §14.5 a without reading outside it. A test with n = 3 says nothing about n = 1000000. A proof needs one statement that covers every iteration at once.

The invariant is that statement. It describes the work done so far in a form that is true at every visit of the loop head: “s is the sum of the first i elements, and i is between 0 and n”. The variables change; the relation between them does not. Each iteration does one more piece of work and moves i so that the sentence is true again. The proof works like a row of dominoes: the first one falls (the statement holds on entry), and each one knocks over the next (one iteration keeps it true), so all of them fall, however long the row. The invariant may be false in the middle of the body, after s has grown but before i has; it is claimed only at the head.

How it works

Write BB for the loop test and II for the candidate invariant. Three checks show that II is an invariant and that it is useful.

  1. Initialization. The code before the loop makes II true.

  2. Preservation, also called consecution. Take any state in which II and BB both hold and run the body once. If the body finishes, II holds again. This check may assume nothing about the state except II and BB; a condition that passes it is called inductive.

  3. Exit. II together with “BB is false” implies the result the loop must deliver.

Induction on the number of iterations then shows that II holds at every arrival at the head, and the exit check gives the result.

The same invariant proves the safety of each operation in the body. At the start of the body both II and BB hold, so a check such as “the index is in range” must follow from II and BB together. Termination is a separate argument. It uses a ranking function §3.25: a quantity computed from the variables that II and BB keep at 0 or above and that every iteration lowers.

Invariants come from people or from tools. Verification tools accept invariants that programmers write as annotations next to the loop, and check the three conditions automatically. Abstract interpretation §3.4 computes invariants without help: interval analysis §3.9 finds 0≤i≤1000 \le i \le 100 for a loop that counts i up to the constant 100. Finding a sufficient invariant automatically is undecidable §19.2.1 in general [159], a consequence of Rice’s theorem §19.2.2, so tools succeed only for restricted kinds of loops and properties.

Worked example

Use the summing loop with n=3n = 3 and a=[4,7,2]a = [4, 7, 2], and the invariant I:0≤i≤n and s=a[0]+…+a[i−1],I:\quad 0 \le i \le n \ \text{ and } \ s = a[0] + \dots + a[i-1], where the sum is 0 when i=0i = 0. The head is reached four times:

The body read a[0], a[1] and a[2], never a[3].

The general proof, writing i′i' and s′s' for the values after one run of the body:

  1. Initialization: before the loop i=0i = 0 and s=0s = 0, and 0≤0≤n0 \le 0 \le n holds whenever n≥0n \ge 0.

  2. Preservation: assume 0≤i≤n0 \le i \le n, i<ni < n and s=a[0]+…+a[i−1]s = a[0] + \dots + a[i-1]. The read a[i] is in range because 0≤i≤n−10 \le i \le n - 1. The body sets s′=s+a[i]s' = s + a[i] and i′=i+1i' = i + 1. Then 0≤i′0 \le i'; i′≤ni' \le n because i<ni < n and both are integers; and s′=a[0]+…+a[i′−1]s' = a[0] + \dots + a[i'-1].

  3. Exit: i≤ni \le n from II and i≥ni \ge n from the failed test give i=ni = n, so ss is the sum of all nn elements.

An off-by-one error shows up as a failed check. With the test i <= n, the body also runs with i=ni = n: the read a[n] lies outside the array, and i′=n+1i' = n + 1 breaks i≤ni \le n. The failed preservation check points at the bug.

Progress needs one more quantity, n−in - i. It takes the values 3, 2, 1 and 0 at the four visits of the head. The invariant keeps it at 0 or above, and each iteration lowers it by 1, so the loop stops after at most nn iterations.

Stated precisely

A Hoare triple §3.31 {P}S{Q}\{P\}\ S\ \{Q\} states: if condition PP holds before statement SS runs and SS finishes, then condition QQ holds afterwards. Let BB be the loop test, SS the body, PP the condition that holds before the loop and QQ the required result; write ∧\land for “and”, ¬\lnot for “not” and ⇒\Rightarrow for “implies”. The while rule of Hoare logic, which Tony Hoare published in 1969, states: from {I∧B}S{I} conclude {I}whileBdoS{I∧¬B}.\text{from } \{I \land B\}\ S\ \{I\} \text{ conclude } \{I\}\ \mathrm{while}\ B\ \mathrm{do}\ S\ \{I \land \lnot B\}. A loop invariant II proves {P}whileBdoS{Q}\{P\}\ \mathrm{while}\ B\ \mathrm{do}\ S\ \{Q\} when P⇒IP \Rightarrow I, {I∧B}S{I}\{I \land B\}\ S\ \{I\}, and I∧¬B⇒QI \land \lnot B \Rightarrow Q.

This is partial correctness: QQ is promised only if the loop finishes. Total correctness also requires termination, which a ranking function ff, an integer expression over the variables, proves with two more conditions: I∧B⇒f≥0I \land B \Rightarrow f \ge 0, and {I∧B∧f=v}S{f<v}\{I \land B \land f = v\}\ S\ \{f < v\} for every integer vv, where vv names the value of ff before the body runs.

The proof depends on three assumptions: every run of the body finishes; nothing outside the body changes the variables between the checks (no other thread, no interrupt handler §6.12, no write through a pointer that refers to a loop variable); and the arithmetic in the proof is the arithmetic the machine performs.

Limits and common mistakes

An invariant can be true and useless. The condition “true” holds at every loop head and proves nothing. A useful invariant is strong enough for the exit check and for every check in the body, yet weak enough to hold on entry.

A condition can hold at every visit of the head and still fail the preservation check. In x = 1; y = 0; while (c) { x = x + y; y = y + 1; }, where c is any condition, the head sees (x,y)=(1,0),(1,1),(2,2),(4,3),(7,4),…(x, y) = (1, 0), (1, 1), (2, 2), (4, 3), (7, 4), \dots, so x≥1x \ge 1 always holds. Preservation cannot be shown from x≥1x \ge 1 alone: the state x=1,y=−5x = 1, y = -5 satisfies it and leads to x=−4x = -4. The strengthened condition x≥1∧y≥0x \ge 1 \land y \ge 0 is inductive, because x+y≥1x + y \ge 1 and y+1≥0y + 1 \ge 0. Proofs often fail for a missing part of the invariant, not a false one.

An invariant does not prove termination. A body that forgets i = i + 1 keeps 0≤i≤n0 \le i \le n true while the loop runs forever.

The proof covers only the arithmetic it assumes. The invariant s=a[0]+…+a[i−1]s = a[0] + \dots + a[i-1] is a statement about mathematical integers. If s is a 32-bit variable, the sum can overflow, and a separate argument must show that it fits, or the invariant must be stated modulo 2322^{32}.

Exits other than the test, such as break or return, do not give ¬B\lnot B; the result must be shown separately at each of them.

Questions answered

What invariant proves both index bounds and progress?

For a loop that steps an index i from 0 up to a length n (i = 0; while (i < n) { ... a[i] ...; i = i + 1; }, with n≥0n \ge 0 and a holding n elements), the invariant 0≤i≤n0 \le i \le n proves the index bounds, and together with the quantity n−in - i it proves progress. At every read, the invariant and the passed test i<ni < n give 0≤i≤n−10 \le i \le n - 1, exactly the valid positions of a. The invariant also gives n−i≥0n - i \ge 0 at every visit of the loop head, and each iteration lowers n−in - i by exactly 1, so the loop exits after nn iterations with i=ni = n.

Strictly, the invariant proves the bounds, and progress comes from the decreasing quantity n−in - i, a ranking function; the invariant supplies its lower bound 0. No invariant proves progress alone: a body that forgets i = i + 1 keeps 0≤i≤n0 \le i \le n true forever. Add to the invariant whatever the result needs, for a sum “s equals the sum of the first i elements”. The argument assumes that i + 1 cannot overflow (true here, because i<ni < n), that nothing changes n or a during the loop, and that each run of the body finishes.

Related entries: Fixed point (§3.22), Ranking function (§3.25), Termination versus time bound (§2.33), Hoare triple (§3.31), Inductive invariant and its three obligations (§19.2.4), Widening and narrowing (§3.23). Further reading: [159, 224].