/* specification: swap x and y Assume: no arithmetic overflow */ x = x + y; y = x - y; x = x - y;
MORAL: the implementation need not resemble the specification.
Ideally, the specification is simpler.
/* specification: * if n > 0 then * s = s + sum of [n,n-1,...,1] * else * no change */ OR /* if n >= 0 and s = 0 then * s = sum of [n,n-1,...,1] */ while (n > 0) { s = s + n; n--; }
MORAL: sometimes a partial specification is better, for simplicity and to focus on the intended use.
/* specification: * if it terminates: x == 1; but does it terminate? */ while (x != 1) { if (x % 2 == 0) x = x/2; else x = 3*x + 1; }
MORAL: a short program may have very complex behavior