if, for, while, etc statements all run the instruction or code block which follows them.
If you have {braces} after a 'for' statement, those braces will be the loop body
If you DON'T have braces, then the loop body is up until the next semicolon.
For example, these two are equivilent:
1 2 3 4 5 6 7 8 9
|
for(number; number >=1; --number) // braces, so everything in the braces is the loop body
{
std::cout << number << std::endl;
}
//========
for(number; number >=1; --number) // no braces, so only the code up to the next semicolon is the loop body
std::cout << number << std::endl;
|
The problem with your code is you have a semicolon after the for loop. Therefore it thinks that the loop has an
empty body
1 2 3 4 5 6 7 8
|
for (number; number >=1; --number)
; // the compiler sees this semicolon as the end of the loop body
// this block has NOTHING to do with the loop. It's run only after the above loop
// completes
{
std::cout << number << std::endl;
}
|
So what happens is your loop counts down 'number' to zero, while doing
nothing each time.
Then after the loop is complete, you cout 'number' (which is zero... so that prints "0")
Then you print "0" again on the line below.
This is why you get two zeros.