Section 3.25

Ranking function

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 n−in - i for a loop that raises ii by 1 until it reaches nn. 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 i<ni < n. 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 1,12,14,18,…1, \tfrac{1}{2}, \tfrac{1}{4}, \tfrac{1}{8}, \dots 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 BB is the loop test and SS the body:

  1. Choose a measure ff of the remaining work, such as n−in - i or hi−lo\mathrm{hi} - \mathrm{lo} for a search range from lo\mathrm{lo} to hi\mathrm{hi}.

  2. Show that f≥0f \ge 0 whenever BB holds, usually with the help of a loop invariant II, a condition known to hold at every visit of the loop head.

  3. Show that one run of SS, started where II and BB hold, ends with ff smaller by at least 1. Use the arithmetic the machine performs, not the arithmetic of mathematics.

  4. Show that each run of SS 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 ff plus 1, and at most the starting value when BB forces f≥1f \ge 1.

Some loops need a tuple instead of a number. Pairs (a,b)(a, b) of natural numbers ordered like words in a dictionary, the lexicographic order §19.3.3 (compare aa first, and bb only when the aa 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 bb and keeps aa, or lowers aa and sets bb to any value. The pair decreases every time, so the loop terminates. No ranking function into the natural numbers exists: from a=1,b=0a = 1, b = 0 the loop can still run 1+b′1 + b' times for any input b′b', 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 28=2562^8 = 256: uint8_t i = 3; while (i >= 0) i = i - 1;. A proof that treats i as a mathematical integer runs: the measure f=if = i is at least 0 whenever the test holds, and each iteration lowers it by 1, so the loop runs at most 3+1=43 + 1 = 4 times. The machine disagrees. The head sees i=3,2,1,0i = 3, 2, 1, 0; then the body computes 0−1=−10 - 1 = -1, which the 8-bit variable stores as −1+256=255-1 + 256 = 255. The measure rose from 0 to 255. The test i≥0i \ge 0 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 i≥1i \ge 1, so i−1i - 1 lies between 0 and 254, and the stored result equals the mathematical one. The head sees 3, 2, 1 and 0, the test 0>00 > 0 fails, and the loop ends after 3 iterations. This matches the bound: the test forces f≥1f \ge 1, 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 255+1255 + 1 is stored as 0. The natural measure 256−i256 - i falls from 256 to 1 and then jumps back to 256.

Stated precisely

Let BB be the loop test and II a loop invariant. Write s→ts \to t when one run of the body, started in a state ss that satisfies II and BB, can end in state tt. A set WW with a strict order ≺\prec is well-founded when there is no infinite sequence w0≻w1≻w2≻…w_0 \succ w_1 \succ w_2 \succ \dots, where w≻w′w \succ w' means w′≺ww' \prec w. A function ff from states to WW is a ranking function for the loop when f(t)≺f(s)f(t) \prec f(s) for every such step s→ts \to t. 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 ff with two conditions, where ∧\land means “and” and ⇒\Rightarrow means “implies”:

  1. I∧B⇒f≥0I \land B \Rightarrow f \ge 0;

  2. every run of the body from a state with I∧BI \land B and f=vf = v ends with f≤v−1f \le v - 1.

Number the iterations k=0,1,2,…k = 0, 1, 2, \dots and let fkf_k be the value of ff when iteration kk starts. Then 0≤fk≤f0−k0 \le f_k \le f_0 - k, so k≤f0k \le f_0, and the loop runs at most f0+1f_0 + 1 iterations.

Both conditions refer to the values the machine stores. For an unsigned variable of ww bits, the stored result of i−1i - 1 is (i−1)mod2w(i - 1) \bmod 2^w, which equals i−1i - 1 only when i≥1i \ge 1, and the stored result of i+1i + 1 equals i+1i + 1 only when i≤2w−2i \le 2^w - 2. Pairs of natural numbers with the lexicographic order, (a,b)≺(a′,b′)(a, b) \prec (a', b') when a<a′a < a', or a=a′a = a' and b<b′b < b', 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 n−in - i 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 264−12^{64} - 1 terminates, but at 10910^9 iterations per second it needs (264−1)/109≈1.84×1010(2^{64} - 1) / 10^9 \approx 1.84 \times 10^{10} 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 ff. If n is a hardware register, a variable shared with another thread, or a value written through another pointer to the same memory, n−in - i can grow while the loop runs.

Questions answered

Can an unsigned counter wrap and invalidate the decrease argument?

Yes. An unsigned counter of ww bits stores every result modulo 2w2^w, so decrementing 0 stores 2w−12^w - 1, the largest value, instead of −1-1. 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 −1-1 where the machine performs an increase to 2w−12^w - 1, 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 i≥0i \ge 0 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 i≥1i \ge 1 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 i≤2w−2i \le 2^w - 2 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).