/* PROOF OF CORRECTNESS: MAX(X,Y): compute the largest of X, Y Proof of Correctness can work on if-then-else too. Here is the rule: Condition Rule: PRE CONDITION if cond then S1; POST CONDITION else S2; POST CONDITION endif POST CONDITION What is this saying? If you go either direction, and you end up with the same CONDITION, then the same CONDITION applies after the entire statement. Here is an example: */ #include int max(int x, int y){ int max; // PRE: true // realy no PRE-CONDITION if (x >= y) // x >= y // must be true, or it wouldn't go this way max = x; // (max = x and max >= y) or ... // left-hand side is true so we can OR with anything else // x < y max = y; // (max = y and max >= x) or ... // left-hand side is true so we can OR with anything // POST: (max = x and max >= y) or (max = y and max >= x) // This condition really is the definition of what a max function should do. return max; } int main() { printf("max(1,2)=%d\n",max(1,2)); } /* There are two subtle aspects to this proof: 1. Note the else branch is: x < y or we might write it as y > x. Since we know that max = y, that means that max > x. So why does the proof say max >= x? The proof is not wrong. If max > x, then it is still the case that max >= x. The reason for doing this is to yield a POST condition which represents the general solution of a max function. If the function had been coded with: if (x > y), then don't really want to end up with a different post-condition. We want to represent the general case where we don't care which way it goes in case of a tie. Both parts are symmetrical. 2. Se see "or ..." in both branches. The purpose of this is to show that, since the left-hand side is known to be true, then anything can be or'd with it. This allows the two directions to be combined into one final POST condition. */