C ++继续语句混乱 [英] C++ Continue Statement Confusion

查看:67
本文介绍了C ++继续语句混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一个旧的C ++入门手册,该入门手册躺在我的床下已经有几年了.在阅读特定章节时,我碰巧遇到了"继续"陈述.我阅读了书中有关它的信息;但是,这本书在细节上有些短.我很好奇,想测试一下继续声明,看看是否可以自己解决更多(尽管现在可能已经过时了,但我仍然对它的工作方式感到好奇).

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).

我了解到 continue语句" 使程序跳过当前迭代中的其余循环,就好像到达了语句块的末尾一样,导致它跳到下一个迭代的开始-(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;
} 

该程序的输出为:

99, 98, 97,

现在,我认为结果将类似于以下内容:

Now, I thought the outcome would be similar to this:

99, 98 , 96 , 95, 94, 93, 92, 91, 90

我认为结果会是这样,因为 continue语句会按照定义跳过97并重新开始迭代,从而在上述结果中输出一系列数字.

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.

本书中的示例有效,但它是通过 for循环执行的.我很好奇为什么它不能与 while循环一起使用,因为它们都是迭代.我只需要解释为什么会这样.预先感谢大家.

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.

推荐答案

正如您所说, continue 跳过了循环主体的其余部分.在这种情况下,其中包括-container [0] ,因此其值不再更改.

As you say, continue skips the rest of the loop body. In this case, that includes --container[0], so its value never changes again.

如果要使用 for 循环,更新其iterator子句中的计数器,则它的行为将与您期望的一样:主体的其余部分将被跳过,但不会迭代./p>

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,

这篇关于C ++继续语句混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆