Definition
A ranking function for a loop is a function that maps the values of the loop’s variables to an element of a well-founded set, most often the natural numbers 0, 1, 2 and so on, and whose value strictly decreases with every iteration. A well-founded set is an ordered set with no infinite strictly decreasing sequence, so a ranking function proves that the loop terminates. A typical example is for a loop that raises by 1 until it reaches . Other names are variant and termination measure.
The idea
A loop invariant §3.24 shows what stays true while a loop runs, but not that the loop stops: while (i < n) {}, with an empty body, keeps every invariant and never ends once . A proof of termination needs something that each iteration uses up. In while (i > 0) i = i - 1; the counter i is used up: each iteration takes one unit, and a whole number that stays at 0 or above cannot shrink forever.
A ranking function generalizes that counter. It measures the remaining work: the number of elements left to process, the length of the rest of a list, the width of a search range. If each iteration lowers the measure by at least 1, and the measure cannot be below 0 while the loop continues, the loop must stop. Being positive and decreasing is not enough on its own: the fractions decrease forever and never reach 0. That is why the measure must take values in a well-founded set, where every strictly decreasing sequence ends.
How it works
To prove that while (B) S terminates, where is the loop test and the body:
Choose a measure of the remaining work, such as or for a search range from to .
Show that whenever holds, usually with the help of a loop invariant , a condition known to hold at every visit of the loop head.
Show that one run of , started where and hold, ends with smaller by at least 1. Use the arithmetic the machine performs, not the arithmetic of mathematics.
Show that each run of itself finishes: inner loops need their own ranking functions, and every called function must return.
The number of iterations is then at most the starting value of plus 1, and at most the starting value when forces .
Some loops need a tuple instead of a number. Pairs of natural numbers ordered like words in a dictionary, the lexicographic order §19.3.3 (compare first, and only when the values are equal), form a well-founded set. In while (a > 0 || b > 0) { if (b > 0) b = b - 1; else { a = a - 1; b = input(); } }, with a, b and every input at least 0, each iteration either lowers and keeps , or lowers and sets to any value. The pair decreases every time, so the loop terminates. No ranking function into the natural numbers exists: from the loop can still run times for any input , so no single number bounds the remaining work.
Termination tools search for ranking functions automatically, for example linear expressions found by linear programming. They cannot succeed on every loop, because termination is undecidable §19.2.1 in general (the halting problem §19.2.2). For while (x > 1) x = (x % 2 == 0) ? x / 2 : 3 * x + 1; over mathematical integers, nobody knows whether the loop ends for every starting value (the Collatz conjecture), so nobody knows a ranking function for it.
Worked example
Take an 8-bit unsigned counter, which holds the values 0 to 255 and stores every result modulo : uint8_t i = 3; while (i >= 0) i = i - 1;. A proof that treats i as a mathematical integer runs: the measure is at least 0 whenever the test holds, and each iteration lowers it by 1, so the loop runs at most times. The machine disagrees. The head sees ; then the body computes , which the 8-bit variable stores as . The measure rose from 0 to 255. The test is always true for an unsigned value, so the loop never ends.
The repair makes the test protect the decrement: uint8_t i = 3; while (i > 0) i = i - 1;. The body now runs only when , so lies between 0 and 254, and the stored result equals the mathematical one. The head sees 3, 2, 1 and 0, the test fails, and the loop ends after 3 iterations. This matches the bound: the test forces , so the count is at most the starting value 3.
Counting up wraps the same way. In for (uint8_t i = 0; i < 256; i++), the test is always true because i never exceeds 255, and is stored as 0. The natural measure falls from 256 to 1 and then jumps back to 256.
Stated precisely
Let be the loop test and a loop invariant. Write when one run of the body, started in a state that satisfies and , can end in state . A set with a strict order is well-founded when there is no infinite sequence , where means . A function from states to is a ranking function for the loop when for every such step . Then no run of the loop performs infinitely many iterations, provided every run of the body finishes.
The usual integer form uses an integer expression with two conditions, where means “and” and means “implies”:
;
every run of the body from a state with and ends with .
Number the iterations and let be the value of when iteration starts. Then , so , and the loop runs at most iterations.
Both conditions refer to the values the machine stores. For an unsigned variable of bits, the stored result of is , which equals only when , and the stored result of equals only when . Pairs of natural numbers with the lexicographic order, when , or and , form a well-founded set. A deterministic loop that terminates from every starting state always has a ranking function into the natural numbers: the number of iterations still to come. The difficulty is finding a formula for it.
Limits and common mistakes
Decreasing is not enough; the order must be well-founded. A measure in the real numbers, or in all the integers including the negative ones, can decrease forever.
The decrease must hold on every path through the body. A continue that skips i = i + 1 leaves unchanged on that path, and the loop can repeat forever.
Signed overflow §4.15 in C is undefined behavior §4.12, not wraparound, so for a signed counter the proof must show that no overflow happens at all.
Termination is not a time bound §2.33. A 64-bit counter counting down from terminates, but at iterations per second it needs seconds, about 585 years. A ranking function bounds the number of iterations, not the time each one takes.
The proof assumes that only the body changes the variables in . If n is a hardware register, a variable shared with another thread, or a value written through another pointer to the same memory, can grow while the loop runs.
Questions answered
Can an unsigned counter wrap and invalidate the decrease argument?
Yes. An unsigned counter of bits stores every result modulo , so decrementing 0 stores , the largest value, instead of . This unsigned wraparound §4.16 turns the decrease that a termination proof relies on into a jump upwards. A proof that treats the counter as a mathematical integer claims a decrease from 0 to where the machine performs an increase to , and so it can “prove” termination of a loop that runs forever. With an 8-bit counter, uint8_t i = 3; while (i >= 0) i = i - 1; passes through 3, 2, 1, 0, 255, 254 and so on forever, because the test is always true for an unsigned value.
The decrease argument stays valid only if the proof shows that no wrap can happen on any iteration: the loop test or the loop invariant must guarantee before each decrement, for example the test i > 0. Then the stored result equals the mathematical one and the measure really falls. Counting up needs the matching check that before each increment; for (uint8_t i = 0; i < 256; i++) never ends, because 255 + 1 is stored as 0. For signed counters in C, overflow is undefined behavior, so the proof must show that it never happens.
Related entries: Loop invariant (§3.24), Unsigned modular arithmetic (§4.16), Instruction budget (fuel) (§2.32), Termination versus time bound (§2.33), Halting problem, Rice’s theorem, and restricted verifiers (§19.2.2), Signed integer overflow (§4.15).