Alex Rivera | Logout

What is an invariant?

Asked 2008-09-21T20:42:21.060
218

The word seems to get used in a number of contexts. The best I can figure is that they mean a variable that can't change. Isn't that what constants/finals (darn you Java!) are for?

Edit
Report

3 Answers

306

An invariant is more "conceptual" than a variable. In general, it's a property of the program state that is always true. A function or method that ensures that the invariant holds is said to maintain the invariant.

For instance, a binary search tree might have the invariant that for every node, the key of the node's left child is less than the node's own key. A correctly written insertion function for this tree will maintain that invariant.

As you can tell, that's not the sort of thing you can store in a variable: it's more a statement about the program. By figuring out what sort of invariants your program should maintain, then reviewing your code to make sure that it actually maintains those invariants, you can avoid logical errors in your code.

answered 2008-09-21T20:48:21.030
44

It is a condition you know to always be true at a particular place in your logic and can check for when debugging to work out what has gone wrong.

answered 2008-09-21T20:44:13.350
25

The magic of wikipedia: Invariant (computer science)

In computer science, a predicate that, if true, will remain true throughout a specific sequence of operations, is called (an) invariant to that sequence.

answered 2008-09-21T20:45:25.700

Your Answer