Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Hoare Logic & Verified Algorithms

Preconditions, postconditions, weakest preconditions and machine-checked proofs.

Java sorts objects with TimSort, and the code had been tested for years. In 2015 a team that set out to prove it correct with a verification tool found that it could crash: an invariant it relied on did not always hold, and an input of 67,108,864 elements broke it. This lesson builds the logic behind such proofs: Hoare triples, weakest preconditions, loop invariants as proof rules, and the tools that check proofs by machine.

What you’ll learn

  • Read and write Hoare triples, and apply the assignment axiom and the composition, conditional, while and consequence rules.
  • Prove a small program totally correct in Hoare logic, with an invariant and a variant.
  • Compute weakest preconditions, and explain soundness, relative completeness and the limits that undecidability imposes.
  • Describe separation logic, and how verification tools are used on real algorithms.

Hoare triples

Hoare (1969), building on Floyd (1967), gave one rule for each construct of a small imperative language, so that a proof follows the shape of the program:

RuleStatement
assignment{Q[E/x]} x:=E {Q}\{Q[E/x]\}\ x := E\ \{Q\}, where Q[E/x]Q[E/x] is QQ with EE substituted for xx
compositionfrom {P} C1 {R}\{P\}\ C_1\ \{R\} and {R} C2 {Q}\{R\}\ C_2\ \{Q\}, infer {P} C1; C2 {Q}\{P\}\ C_1;\, C_2\ \{Q\}
conditionalfrom {P∧B} C1 {Q}\{P \land B\}\ C_1\ \{Q\} and {P∧¬B} C2 {Q}\{P \land \lnot B\}\ C_2\ \{Q\}, infer {P}\{P\} if BB then C1C_1 else C2C_2 {Q}\{Q\}
whilefrom {I∧B} C {I}\{I \land B\}\ C\ \{I\}, infer {I}\{I\} while BB do CC {I∧¬B}\{I \land \lnot B\}
consequencefrom P⇒P′P \Rightarrow P', {P′} C {Q′}\{P'\}\ C\ \{Q'\} and Q′⇒QQ' \Rightarrow Q, infer {P} C {Q}\{P\}\ C\ \{Q\}
The while rule is the loop-invariant method: II is the invariant, the premise is maintenance, and the conclusion delivers II plus the negated condition at exit. Initialization and the final step to the postcondition come from the consequence rule.

The assignment axiom runs backward, which surprises everyone once. To guarantee x>5x > 5 after x := x + 1, substitute: the precondition is x+1>5x + 1 > 5, that is x>4x > 4. The tempting forward version, "{P} x:=E {P∧x=E}\{P\}\ x := E\ \{P \land x = E\}", is wrong whenever EE mentions xx: after x := x + 1 the claim x=x+1x = x + 1 is false.

Check your understanding

What is the weakest precondition PP that makes {P}  y:=y+x; x:=2x  {x+y>10}\{P\}\ \ y := y + x;\ x := 2x\ \ \{x + y > 10\} valid?

  1. x+y>10x + y > 10
  2. 2x+y>102x + y > 10
  3. 3x+y>103x + y > 10
  4. 3x+2y>103x + 2y > 10
Show the answer

C. 3x+y>103x + y > 10

Work backward. Through x:=2xx := 2x, the postcondition x+y>10x + y > 10 becomes 2x+y>102x + y > 10. Through y:=y+xy := y + x, that becomes 2x+(y+x)>102x + (y + x) > 10, which is 3x+y>103x + y > 10. Running the program from every start with ∣x∣≤20|x| \le 20 and ∣y∣≤40|y| \le 40 agrees.

A complete proof

Hoare's 1969 paper proved exactly this program: integer division of xx by yy by repeated subtraction.

text
{ x >= 0  and  y > 0 }
r := x; q := 0;
while y <= r do
    r := r - y; q := q + 1
{ x = q*y + r  and  0 <= r < y }
DerivationProof of total correctness
  1. I  ≡  x=q y+r  ∧  r≥0I \;\equiv\; x = q\,y + r \;\land\; r \ge 0

    Choose the invariant: what the loop has achieved, plus the bound that will make r<yr < y meaningful at the end.

  2. I[0/q][x/r]  ≡  x=0⋅y+x  ∧  x≥0⟸x≥0∧y>0I[0/q][x/r] \;\equiv\; x = 0 \cdot y + x \;\land\; x \ge 0 \quad\Longleftarrow\quad x \ge 0 \land y > 0

    Initialization. Push II backward through q := 0, then r := x, with the assignment axiom; the precondition implies the result, so consequence applies:

  3. I[q+1/q][r−y/r]  ≡  x=(q+1) y+(r−y)∧r−y≥0  ≡  x=qy+r∧r≥y⟸I∧y≤rI[q{+}1/q][r{-}y/r] \;\equiv\; x = (q+1)\,y + (r - y) \land r - y \ge 0 \;\equiv\; x = qy + r \land r \ge y \quad\Longleftarrow\quad I \land y \le r

    Maintenance. Push II backward through the body, and check that II together with the loop condition implies it:

  4. x=qy+r  ∧  r≥0  ∧  r<yx = qy + r \;\land\; r \ge 0 \;\land\; r < y

    Exit. The while rule gives I∧¬(y≤r)I \land \lnot(y \le r), which is the postcondition:

  5. r∈N,r  ↦  r−y  <  rr \in \mathbb{N}, \qquad r \;\mapsto\; r - y \;<\; r

    Termination. The variant rr is a natural number by II, and each iteration lowers it by y>0y > 0. The precondition y>0y > 0 is needed only here: with y=0y = 0 the partial-correctness proof still goes through, and the loop runs forever.

Weakest preconditions, and the limits

Dijkstra (1975) turned the rules into a calculus. The weakest precondition wp(C,Q)wp(C, Q) is the weakest assertion that guarantees that CC terminates in a state satisfying QQ, so that [P] C [Q][P]\ C\ [Q] holds exactly when P⇒wp(C,Q)P \Rightarrow wp(C, Q). For loop-free code it is computed mechanically, backward:

wp(x:=E, Q)=Q[E/x]wp(C1; C2, Q)=wp(C1, wp(C2,Q))wp(if B then C1 else C2, Q)=(B⇒wp(C1,Q))∧(¬B⇒wp(C2,Q))\begin{aligned} wp(x := E,\ Q) &= Q[E/x]\\ wp(C_1;\, C_2,\ Q) &= wp\big(C_1,\ wp(C_2, Q)\big)\\ wp(\textbf{if } B \textbf{ then } C_1 \textbf{ else } C_2,\ Q) &= \big(B \Rightarrow wp(C_1, Q)\big) \land \big(\lnot B \Rightarrow wp(C_2, Q)\big) \end{aligned}
Loops are the exception: their weakest precondition is a fixed point that cannot be computed in general, so verifiers ask for the invariant and check it instead.

This is how modern verifiers work. The programmer writes the specification and the loop invariants; the tool computes weakest preconditions backward through each loop-free stretch and emits verification conditions, formulas such as I∧B⇒wp(body,I)I \land B \Rightarrow wp(\text{body}, I); an automatic theorem prover, usually an SMT solver, discharges them or reports which one fails.

How good is the logic itself? It is sound: every derivable triple is true. Cook (1978) proved it relatively complete: every true triple is derivable, provided the assertion language can express the invariants needed and every true statement of the underlying arithmetic may be used as an axiom. The proviso cannot be dropped, since no proof system derives all truths of arithmetic (Gödel), and some richer language features admit no sound and relatively complete Hoare logic at all (Clarke, 1979).

Verified algorithms in practice

Pointers. Hoare logic assumes that different variables name different storage, which fails with pointers: after p.next = q, every other name for the same node sees the change. Separation logic (O'Hearn, Reynolds & Yang, 2001; Reynolds, 2002) adds a separating conjunction P∗QP * Q, meaning "PP and QQ hold of disjoint parts of the heap", and the frame rule: from {P} C {Q}\{P\}\ C\ \{Q\} infer {P∗R} C {Q∗R}\{P * R\}\ C\ \{Q * R\} when CC does not modify the variables of RR. A proof about one list then stays valid next to any other data, and the idea underlies industrial analyzers such as Meta's Infer.

Tools. Auto-active verifiers such as Dafny and Why3 take code with annotations and discharge the verification conditions automatically. Interactive proof assistants, Coq (renamed Rocq in 2025), Isabelle/HOL and Lean, check every proof step against a small trusted kernel. Landmarks include the CompCert optimizing C compiler (Leroy, 2009) and the seL4 operating-system kernel (Klein et al., 2009), both with machine-checked proofs that the implementation meets its specification.

Key takeaways

  • A Hoare triple {P} C {Q}\{P\}\ C\ \{Q\} promises QQ after CC whenever CC starts in PP and terminates; the total-correctness triple [P] C [Q][P]\ C\ [Q] also promises termination.
  • The assignment axiom substitutes backward, {Q[E/x]} x:=E {Q}\{Q[E/x]\}\ x := E\ \{Q\}; the while rule is the loop-invariant method; consequence glues the steps together.
  • Weakest preconditions compute proof obligations backward through loop-free code, and verifiers turn annotated programs into verification conditions for SMT solvers.
  • Hoare logic is sound and relatively complete (Cook, 1978), but correctness is undecidable in general (Rice, Turing), so people supply invariants and machines check them.
  • Separation logic extends the method to pointers, and proof tools have verified compilers, kernels and library algorithms, and found a real bug in TimSort.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

What is the weakest precondition PP that makes {P} x:=x+1 {x>5}\{P\}\ x := x + 1\ \{x > 5\} valid, for an integer xx?

  1. x>5x > 5
  2. x>4x > 4
  3. x>6x > 6
  4. x=5x = 5
Show the answer

B. x>4x > 4

Substitute x+1x + 1 for xx in the postcondition: x+1>5x + 1 > 5, that is x>4x > 4, or x≥5x \ge 5 over the integers.

Question 2

Which of these triples is valid?

  1. {true} while true do skip {false}\{\text{true}\}\ \text{while true do skip}\ \{\text{false}\}
  2. {x=1} x:=x+1 {x=1}\{x = 1\}\ x := x + 1\ \{x = 1\}
  3. [true] while true do skip [false][\text{true}]\ \text{while true do skip}\ [\text{false}]
  4. {true} x:=1 {x=2}\{\text{true}\}\ x := 1\ \{x = 2\}
Show the answer

A. {true} while true do skip {false}\{\text{true}\}\ \text{while true do skip}\ \{\text{false}\}

The loop never terminates, and a partial-correctness triple promises nothing about runs that do not end, so even the postcondition "false" is vacuously guaranteed. The total-correctness version is invalid, because it promises termination.

Question 3

To apply the while rule to while B do C with invariant II, what must you prove about the body CC?

  1. {I} C {I}\{I\}\ C\ \{I\}, for every starting state
  2. {I∧B} C {I}\{I \land B\}\ C\ \{I\}
  3. {B} C {¬B}\{B\}\ C\ \{\lnot B\}
  4. {I∧¬B} C {I}\{I \land \lnot B\}\ C\ \{I\}
Show the answer

B. {I∧B} C {I}\{I \land B\}\ C\ \{I\}

The body runs only when BB holds, so you may assume I∧BI \land B, and you must re-establish II. The rule then delivers I∧¬BI \land \lnot B after the loop.

Question 4

Why do verifiers such as Dafny ask the programmer for loop invariants instead of always finding them automatically?

  1. Because invariants are only documentation
  2. Because SMT solvers cannot handle arithmetic
  3. Because correctness is undecidable in general (Rice's theorem), so no tool can always find the invariants
  4. Because loops have no weakest preconditions
Show the answer

C. Because correctness is undecidable in general (Rice's theorem), so no tool can always find the invariants

If invariants could always be computed, correctness and termination would be decidable, contradicting Rice's theorem and the halting problem. Tools infer many simple invariants and check the rest, but the general problem has no algorithm.

Further reading

  • C. A. R. Hoare, "An axiomatic basis for computer programming," Communications of the ACM 12(10) (1969).
  • E. W. Dijkstra, "Guarded commands, nondeterminacy and formal derivation of programs," Communications of the ACM 18(8) (1975).
  • S. A. Cook, "Soundness and completeness of an axiom system for program verification," SIAM Journal on Computing 7(1) (1978).
  • J. C. Reynolds, "Separation logic: A logic for shared mutable data structures," Proceedings of LICS (2002).
  • S. de Gouw, J. Rot, F. S. de Boer, R. Bubel & R. Hähnle, "OpenJDK's java.utils.Collection.sort() is broken: The good, the bad and the worst case," Proceedings of CAV (2015).