I am currently going through Accelerated C ++ and just came across this in chapter 3:
// invariant: // we have read count grades so far, and // sum is the sum of the first count grades while (cin >> x) { ++count; sum += x; }
The authors follow this, explaining that the invariant needs special attention to it, because when the input is read at x , we will read the estimates count + 1 and, therefore, the invariant will be incorrect. Similarly, when we increase the count, sum will no longer be the sum of the latest grades (if you haven’t guessed, this is a traditional program for calculating student grades).
I do not understand why this matters. Of course, for any other loop such a statement would be true? For example, here is the first cycle of the while book (the output is filled later):
Once we have written the appropriate output line, of course, the invariant will be false until we increase r , as in another example?
How do these two conditions differ?
EDIT: Thanks for all your answers. I think I have this, but I'm going to leave it a little longer before choosing “Accepted Answer” to be sure. So far, all answers basically agree, so it hardly seems fair, but worth doing, I think.
Original paragraph as follows:
“Understanding the invariant for this cycle requires special attention because the condition at the time has side effects. These side effects affect the truth of the invariant: successful execution of cin → x does the first part of the invariant - the part that says that we read the estimates of the estimates is false. Accordingly, we must modify our analysis to explain the effect that this condition may have on the invariant.
We know that the invariant was true before evaluating the condition, so we know that we have already read the graphs of estimates. If cin → x succeeds, we now read the count + 1 classes. We can turn this part of the invariant back on by increasing the counter. However, this does falsify the second part of the invariant - the part that says that the sum is the sum of the first estimates of the graph, because after we increase the score, the sum now represents the sum of the first count - 1 estimate, not the first count. Fortunately, we can make the second part of the invariant true by doing the sum + = x; so that the whole invariant will be true during subsequent outages after a while.
If the condition is false, this means that our input attempt failed, so we have not received more data, and therefore the invariant is still true. As a result, we do not need to consider the side effects of the condition after completion. "