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 for the loop test and for the candidate invariant. Three checks show that is an invariant and that it is useful.
Initialization. The code before the loop makes true.
Preservation, also called consecution. Take any state in which and both hold and run the body once. If the body finishes, holds again. This check may assume nothing about the state except and ; a condition that passes it is called inductive.
Exit. together with “ is false” implies the result the loop must deliver.
Induction on the number of iterations then shows that 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 and hold, so a check such as “the index is in range” must follow from and together. Termination is a separate argument. It uses a ranking function §3.25: a quantity computed from the variables that and 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 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 and , and the invariant where the sum is 0 when . The head is reached four times:
, : , and the empty sum is 0.
, : .
, : .
, : . The test is false, so the loop exits.
The body read a[0], a[1] and a[2], never a[3].
The general proof, writing and for the values after one run of the body:
Initialization: before the loop and , and holds whenever .
Preservation: assume , and . The read
a[i]is in range because . The body sets and . Then ; because and both are integers; and .Exit: from and from the failed test give , so is the sum of all elements.
An off-by-one error shows up as a failed check. With the test i <= n, the body also runs with : the read a[n] lies outside the array, and breaks . The failed preservation check points at the bug.
Progress needs one more quantity, . 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 iterations.
Stated precisely
A Hoare triple §3.31 states: if condition holds before statement runs and finishes, then condition holds afterwards. Let be the loop test, the body, the condition that holds before the loop and the required result; write for “and”, for “not” and for “implies”. The while rule of Hoare logic, which Tony Hoare published in 1969, states: A loop invariant proves when , , and .
This is partial correctness: is promised only if the loop finishes. Total correctness also requires termination, which a ranking function , an integer expression over the variables, proves with two more conditions: , and for every integer , where names the value of 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 , so always holds. Preservation cannot be shown from alone: the state satisfies it and leads to . The strengthened condition is inductive, because and . 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 true while the loop runs forever.
The proof covers only the arithmetic it assumes. The invariant 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 .
Exits other than the test, such as break or return, do not give ; 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 and a holding n elements), the invariant proves the index bounds, and together with the quantity it proves progress. At every read, the invariant and the passed test give , exactly the valid positions of a. The invariant also gives at every visit of the loop head, and each iteration lowers by exactly 1, so the loop exits after iterations with .
Strictly, the invariant proves the bounds, and progress comes from the decreasing quantity , a ranking function; the invariant supplies its lower bound 0. No invariant proves progress alone: a body that forgets i = i + 1 keeps 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 ), 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].