In reading accelerated c++ I was confused by the explanation given for why the invariant becomes false (see code below):
The invariant is defined by the author (in this case) as:
The invariant for our while is that we have written r rows of output so far. When we define r, we give it an initial value of 0. At this point, we haven’t written anything at all. Setting r to 0 obviously makes the invariant true, so we have met the first requirement.
// invariant: we have written r rows so far
int r = 0;
// setting r to 0 makes the invariant true
while (r != rows) {
// we can assume that the invariant is true here
// writing a row of output makes the invariant false <- WHY?
std::cout << std::endl;
// incrementing r makes the invariant true again
++r;
}
// we can conclude that the invariant is true here
Then later explains…
Writing a row of output causes the invariant to become false, because r is no longer the number of rows we have written
Given the definition i can’t form a connection between the two.
Why does the invariant become false when a row of output is writing?
ris defined to be the number of rows that have been printed. Therefore, the invariant is true only whenBetween when you print a row and when you increment
rto update the number of rows printed so far, that invariant is not true.ris equal to some number (say,n), and the “number of rows that have been printed” is one larger than that number (n + 1), because of the row you just printed. Therefore, the invariant is not true becausen != n + 1.