# Loop invariant

In computer science, a **loop invariant** is a property of a program loop that is true before (and after) each iteration. It is a logical assertion, sometimes checked within the code by an assertion call. Knowing its invariant(s) is essential in understanding the effect of a loop.

In formal program verification, particularly the Floyd-Hoare approach, loop invariants are expressed by formal predicate logic and used to prove properties of loops and by extension algorithms that employ loops (usually correctness properties). The loop invariants will be true on entry into a loop and following each iteration, so that on exit from the loop both the loop invariants and the loop termination condition can be guaranteed.

From a programming methodology viewpoint, the loop invariant can be viewed as a more abstract specification of the loop, which characterizes the deeper purpose of the loop beyond the details of this implementation. A survey article ^{[1]} covers fundamental algorithms from many areas of computer science (searching, sorting, optimization, arithmetic etc.), characterizing each of them from the viewpoint of its invariant.

Because of the similarity of loops and recursive programs, proving partial correctness of loops with invariants is very similar to proving correctness of recursive programs via induction. In fact, the loop invariant is often the same as the inductive hypothesis to be proved for a recursive program equivalent to a given loop.

## Informal example

The following C subroutine `max()`

returns the maximum value in its argument array `a[]`

, provided its length `n`

is at least 1.
Comments are provided at lines 3, 6, 9, 11, and 13. Each comment makes an assertion about the values of one or more variables at that stage of the function.
The highlighted assertions within the loop body, at the beginning and end of the loop (lines 6 and 11), are exactly the same. They thus describe an invariant property of the loop.
When line 13 is reached, this invariant still holds, and it is known that the loop condition `i!=n`

from line 5 has become false. Both properties together imply that `m`

equals the maximum value in `a[0...n-1]`

, that is, that the correct value is returned from line 14.

int max(int n, const int a[]) { int m = a[0]; // m equals the maximum value in a[0...0] int i = 1; while (i != n) { // m equals the maximum value in a[0...i-1] if (m < a[i]) m = a[i]; // m equals the maximum value in a[0...i] ++i; // m equals the maximum value in a[0...i-1] } // m equals the maximum value in a[0...i-1], and i==n return m; }

Following a defensive programming paradigm, the loop condition `i!=n`

in line 5 should better be modified to `i<n`

, in order to avoid endless looping for illegitimate negative values of `n`

. While this change in code intuitively shouldn't make a difference, the reasoning leading to its correctness becomes somewhat more complicated, since then only `i>=n`

is known in line 13. In order to obtain that also `i<=n`

holds, that condition has to be included into the loop invariant. It is easy to see that `i<=n`

, too, is an invariant of the loop, since `i<n`

in line 6 can be obtained from the (modified) loop condition in line 5, and hence `i<=n`

holds in line 11 after `i`

has been incremented in line 10. However, when loop invariants have to be manually provided for formal program verification, such intuitively too obvious properties like `i<=n`

are often overlooked.

## Floyd–Hoare logic

In Floyd–Hoare logic,^{[2]}^{[3]} the partial correctness of a while loop is governed by the following rule of inference:

- [math]\displaystyle{ \frac{\{C\land I\}\;\mathrm{body}\;\{I\}} {\{I\}\;\mathbf{while}\ (C)\ \mathrm{body}\;\{\lnot C\land I\}} }[/math]

This means:

- If some property [math]\displaystyle{ I }[/math] is preserved by the code [math]\displaystyle{ \mathrm{body} }[/math] —more precisely, if [math]\displaystyle{ I }[/math] holds after the execution of [math]\displaystyle{ \mathrm{body} }[/math] whenever both [math]\displaystyle{ C }[/math] and [math]\displaystyle{ I }[/math] held beforehand—
*(upper line)*then - [math]\displaystyle{ C }[/math] and [math]\displaystyle{ I }[/math] are guaranteed to be false and true, respectively, after the execution of the whole loop [math]\displaystyle{ \mathbf{while}\ (C)\ \mathrm{body} }[/math], provided [math]\displaystyle{ I }[/math] was true before the loop
*(lower line)*.

In other words: The rule above is a deductive step that has as its premise the Hoare triple [math]\displaystyle{ \{C\land I\}\;\mathrm{body}\;\{I\} }[/math]. This triple is actually a relation on machine states. It holds whenever starting from a state in which the boolean expression [math]\displaystyle{ C\land I }[/math] is true and successfully executing some code called [math]\displaystyle{ \mathrm{body} }[/math], the machine ends up in a state in which [math]\displaystyle{ I }[/math] is true. If this relation can be proven, the rule then allows us to conclude that successful execution of the program [math]\displaystyle{ \mathbf{while}\ (C)\ \mathrm{body} }[/math] will lead from a state in which [math]\displaystyle{ I }[/math] is true to a state in which [math]\displaystyle{ \lnot C\land I }[/math] holds. The boolean formula [math]\displaystyle{ I }[/math] in this rule is called a loop invariant.

### Example

The following example illustrates how this rule works. Consider the program

while (x < 10) x := x+1;

One can then prove the following Hoare triple:

- [math]\displaystyle{ \{x\leq10\}\; \mathbf{while}\ (x\lt 10)\ x := x+1\;\{x=10\} }[/math]

The condition *C* of the `while`

loop is [math]\displaystyle{ x\lt 10 }[/math]. A useful loop invariant [math]\displaystyle{ I }[/math] has to be guessed; it will turn out that [math]\displaystyle{ x\leq10 }[/math] is appropriate. Under these assumptions it is possible to prove the following Hoare triple:

- [math]\displaystyle{ \{x\lt 10 \land x\leq10\}\; x := x+1 \;\{x\leq10\} }[/math]

While this triple can be derived formally from the rules of Floyd-Hoare logic governing assignment, it is also intuitively justified: Computation starts in a state where [math]\displaystyle{ x\lt 10 \land x\leq10 }[/math] is true, which means simply that [math]\displaystyle{ x\lt 10 }[/math] is true. The computation adds 1 to [math]\displaystyle{ x }[/math], which means that [math]\displaystyle{ x\leq10 }[/math] is still true (for integer x).

Under this premise, the rule for `while`

loops permits the following conclusion:

- [math]\displaystyle{ \{x\leq10\}\; \mathbf{while}\ (x\lt 10)\ x := x+1 \;\{\lnot(x\lt 10) \land x\leq10\} }[/math]

However, the post-condition [math]\displaystyle{ \lnot(x\lt 10)\land x\leq10 }[/math] ([math]\displaystyle{ x }[/math] is less than or equal to 10, but it is not less than 10) is logically equivalent to [math]\displaystyle{ x=10 }[/math], which is what we wanted to show.

The property [math]\displaystyle{ 0 \leq x }[/math] is another invariant of the example loop, and the trivial property [math]\displaystyle{ \mathrm{true} }[/math] is another one. Applying the above inference rule to the former invariant yields [math]\displaystyle{ \{0 \leq x\}\; \mathbf{while}\ (x\lt 10)\ x := x+1\;\{10 \leq x\} }[/math]. Applying it to invariant [math]\displaystyle{ \mathrm{true} }[/math] yields [math]\displaystyle{ \{\mathrm{true}\}\; \mathbf{while}\ (x\lt 10)\ x := x+1\;\{10 \leq x\} }[/math], which is slightly more expressive.

## Programming language support

### Eiffel

The Eiffel programming language provides native support for loop invariants.^{[4]} A loop invariant is expressed with the same syntax used for a class invariant. In the sample below, the loop invariant expression `x <= 10`

must be true following the loop initialization, and after each execution of the loop body; this is checked at runtime.

from x := 0 invariant x <= 10 until x > 10 loop x := x + 1 end

### Whiley

The Whiley programming language also provides first-class support for loop invariants.^{[5]} Loop invariants are expressed using one or more `where`

clauses, as the following illustrates:

function max(int[] items) -> (int r) // Requires at least one element to compute max requires |items| > 0 // (1) Result is not smaller than any element ensures all { i in 0..|items| | items[i] <= r } // (2) Result matches at least one element ensures some { i in 0..|items| | items[i] == r }: // nat i = 1 int m = items[0] // while i < |items| // (1) No item seen so far is larger than m where all { k in 0..i | items[k] <= m } // (2) One or more items seen so far matches m where some { k in 0..i | items[k] == m }: if items[i] > m: m = items[i] i = i + 1 // return m

The `max()`

function determines the largest element in an integer array. For this to be defined, the array must contain at least one element. The postconditions of `max()`

require that the returned value is: (1) not smaller than any element; and, (2) that it matches at least one element. The loop invariant is defined inductively through two `where`

clauses, each of which corresponds to a clause in the postcondition. The fundamental difference is that each clause of the loop invariant identifies the result as being correct up to the current element `i`

, whilst the postconditions identify the result as being correct for all elements.

## Use of loop invariants

A loop invariant can serve one of the following purposes:

- purely documentary
- to be checked within in the code by an assertion call
- to be verified based on the Floyd-Hoare approach

For 1., a natural language comment (like `// m equals the maximum value in a[0...i-1]`

in the above example) is sufficient.

For 2., programming language support is required, such as the C library assert.h, or the above-shown `invariant`

clause in Eiffel. Often, run-time checking can be switched on (for debugging runs) and off (for production runs) by a compiler or a runtime option.(citation?)

For 3., some tools exist to support mathematical proofs, usually based on the above-shown Floyd–Hoare rule, that a given loop code in fact satisfies a given (set of) loop invariant(s).

The technique of abstract interpretation can be used to detect loop invariant of given code automatically. However, this approach is limited to very simple invariants (such as `0<=i && i<=n && i%2==0`

).

## Distinction from loop-invariant code

A loop invariant (loop-invariant *property*) is to be distinguished from loop-invariant *code*; note "loop invariant" (noun) versus "loop-invariant" (adjective).
Loop-invariant code consists of statements or expressions that can be moved outside the body of a loop without affecting the semantics of a program; such transformations, called loop-invariant code motion, are performed by some compilers to optimize programs.
A loop-invariant code example (in the C programming language) is

for (int i=0; i<n; ++i) { x = y+z; a[i] = 6*i + x*x; }

where the calculations `x = y+z`

and `x*x`

can be moved before the loop, resulting in an equivalent, but faster, program:

x = y+z; t1 = x*x; for (int i=0; i<n; ++i) { a[i] = 6*i + t1; }

In contrast, e.g. the property `0<=i && i<=n`

is a loop invariant for both the original and the optimized program, but is not part of the code, hence it doesn't make sense to speak of "moving it out of the loop".

Loop-invariant code may induce a corresponding loop-invariant property.^{[clarification needed]} For the above example, the easiest way to see it is to consider a program where the loop invariant code is computed both before and within the loop:

x1 = y+z; t1 = x1*x1; for (int i=0; i<n; ++i) { x2 = y+z; a[i] = 6*i + t1; }

A loop-invariant property of this code is `(x1==x2 && t1==x2*x2) || i==0`

, indicating that the values computed before the loop agree with those computed within (except before the first iteration).(citation?)

## See also

- Invariant (computer science)
- Loop-invariant code motion
- Loop variant
- Weakest-preconditions of While loop

## References

- ↑ Carlo A. Furia, [Bertrand Meyer] and Sergey Velder. "Loop invariants: analysis, classification, and examples."ACM Computing Surveys. vol. 46, no. 3, February 2014([1]
- ↑ Robert W. Floyd (1967). "Assigning Meanings to Programs". in J.T. Schwartz.
*Proceedings of Symposia in Applied Mathematics*. Mathematical Aspects of Computer Science.**19**. Providence, RI: American Mathematical Society. pp. 19–32. http://www.cse.chalmers.se/edu/year/2017/course/TDA384_LP1/files/lectures/additional-material/AssigningMeanings1967.pdf. - ↑ Hoare, C. A. R. (October 1969). "An axiomatic basis for computer programming".
*Communications of the ACM***12**(10): 576–580. doi:10.1145/363235.363259. http://www.spatial.maine.edu/~worboys/processes/hoare%20axiomatic.pdf. - ↑ Meyer, Bertrand,
*Eiffel: The Language,*Prentice Hall, 1991, pp. 129–131. - ↑ Pearce, David J.; Groves, Lindsay (2015). "Designing a Verifying Compiler: Lessons Learned from Developing Whiley".
*Science of Computer Programming***113**: 191–220. doi:10.1016/j.scico.2015.09.006.

## Further reading

- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein.
*Introduction to Algorithms*, Second Edition. MIT Press and McGraw-Hill, 2001. ISBN:0-262-03293-7. Pages 17–19, section 2.1: Insertion sort. - David Gries. "A note on a standard strategy for developing loop invariants and loops."
*Science of Computer Programming*, vol 2, pp. 207–214. 1984. - Michael D. Ernst, Jake Cockrell, William G. Griswold, David Notkin. "Dynamically Discovering Likely Program Invariants to Support Program Evolution."
*International Conference on Software Engineering*, pp. 213–224. 1999. - Robert Paige. "Programming with Invariants."
*IEEE Software*, 3(1):56–69. January 1986. - Yanhong A. Liu, Scott D. Stoller, and Tim Teitelbaum. Strengthening Invariants for Efficient Computation.
*Science of Computer Programming*, 41(2):139–172. October 2001. - Michael Huth, Mark Ryan. "Logic in Computer Science.", Second Edition.

Original source: https://en.wikipedia.org/wiki/ Loop invariant.
Read more |