您对循环不变量的定义并不完全正确。本质上,它应该只在每次循环重复之前和之后才成立。维基百科有很好的定义。
这个循环的不变量是:the values[x] and values[x + 1] are maybe not sorted or x is the last index
在每次循环迭代之前和之后都是真的。在循环结合for 循环条件之后它仍然是正确的:false
i, temp : integer;
values : array[1..100] of integer;
x := 1;
while x < 100 loop
// the values[x] and values[x + 1] are maybe not sorted or x is the last index - true
if values[x] > values[x+1] then begin
temp := values[x];
values[x] := values[x+1];
values[x+1] := temp;
end if;
x := x + 1;
// the values[x] and values[x + 1] are maybe not sorted or x is the last index - true
end loop;
// the values[x] and values[x + 1] are maybe not sorted or x is the last index - true
// and x >= 100 - true
自然,循环不变量应该与循环体及其执行的任务相关。循环不变量确保在循环的每个步骤中,循环体执行的条件相同。