I just bought "Accelerated C++ -Practical programming by example"
It seems like a great book... but i'm really confused about something:
On page 21 (for those of you that have the book)
They explain how a "while loop" works (which btw. i already know) but they seem to have said something really weird. Here is the code in the book:
Code:
// 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
std::cout << std::endl;
// incrementing r makes the invariant true again
++r;
}
// we can conclude that the invariant is true here
Now I'm really confused; as I understand it when they refer to "the invariant" they are reffering to r not equalling rows, they previously declared rows to be an integer equal to 5 (on page 18):
Code:
// the number of blanks surrounding the greeting
const int pad = 1;
// total number of rows to write
const int rows = pad * 2 + 3;
So my question is why is the invariant made false by outputting a newline?? Surely its not, surely if i didn't include the "++r;" rather than the while loop stopping as seem's to be implied it would go on for ever......... what am I missing?
EDIT: I get it, i was misunderstanding what they meant by invariant.... still fail to see its uses, loops seem pretty easy to understand without these invariant things.