سؤال

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?

هل كانت مفيدة؟

المحلول

r is defined to be the number of rows that have been printed. Therefore, the invariant is true only when

r == number of rows that have been printed

Between when you print a row and when you increment r to update the number of rows printed so far, that invariant is not true.

r is 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 because n != n + 1.

نصائح أخرى

we have written r rows of output so far

r starts as 0, and at the point where the cout is r is still 0. The cout has written 1 line but r is 0. Therefore the invariant is temporarilly false because if you plug in the value of r into the statement above, it is untrue that "we have written out 0 rows of output so far".

Incrementing r causes the invariant to become true again.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top