问题
Background
I was reading an old C++ primer that I have had lying underneath my bed for a few years. While reading a particular chapter, I happened to come across the "continue" statement. I read the information in the book about it; however, the book was a little short on details. I, being curious, wanted to test the continue statement to see if I could figure out more about it on my own (although it may be obsolete now, I still am curious on how it works).
Problem
I read that the continue statement "causes the program to skip the rest of the loop in the current iteration, as if the end of the statement block had been reached, causing it to jump to the start of the following iteration -- (cplusplus.com)"
With that being said, I constructed this simple program to test it:
#include <iostream>
int main(void) {
unsigned short int amount = 100;
unsigned short int container[5] = {amount , 0, 0, 0, 0,};
while(!(container[0]==90))
{
if(container[0]==97) continue;
std::cout << --container[0] << ", ";
}
return 0;
}
The output for this program is:
99, 98, 97,
Now, I thought the outcome would be similar to this:
99, 98 , 96 , 95, 94, 93, 92, 91, 90
I thought the outcome would be this since the continue statement would skip, by definition, the 97 and restart the iteration, thus outputting the series of numbers in the above outcome.
The example in the book works, but it is performed with a for loop. I was curious as to why it does not work with a while loop since they are both iterations. I just need some explanation as to why this is. Thanks to everyone in advance.
回答1:
As you say, continue
skips the rest of the loop body. In this case, that includes --container[0]
, so its value never changes again.
If you were to use a for
loop, updating the counter in its iterator clause, then it would behave as you expect: the remainder of the body would be skipped, but not the iterator.
for (container[0] = 99; container[0] != 90; --container[0]) {
if (container[0] == 97) continue; // skip "cout", jump to "--"
std::cout << container[0] << ", ";
}
// Output: 99, 98, 96, 95, 94, 93, 92, 91,
来源:https://stackoverflow.com/questions/21248454/c-continue-statement-confusion