3.2.2 for循环的变体(3)
执行循环内部的continue语句将跳过循环体中其他剩余的语句,而立即启动下一次循环迭代。可以用下面的代码来示范continue语句的作用:
- #include <iostream>
- using std::cin;
- using std::cout;
- using std::endl;
- int main()
- {
- int value(0), product(1);
- for(int i = 1; i <= 10; i++)
- {
- cout << "Enter an integer: ";
- cin >> value;
- if(0 == value) // If value is zero
- continue; // skip to next iteration
- product *= value;
- }
- cout << "Product (ignoring zeros): " << product
- << endl;
- return 0; // Exit from loop
- }
该循环读取10个数值,目的是得到输入值的乘积。if语句检查每个输入值,如果是0,则continue语句跳到下一次迭代。这样,即使某个输入值为0,也不会得到等于0的乘积。显然,如果最后一次迭代时输入值为0,则该循环将结束。当然还有其他一些方法可以得到相同的结果,但continue语句提供了非常有用的功能,特别是在需要从循环体的不同位置跳到当前迭代结束处这样的复杂循环中。
在for循环的逻辑中,break和continue语句的作用如图3-4所示。
显然,在实际情况中将在某些条件测试逻辑中使用break和continue语句,以确定何时应该退出循环,或者何时应该跳过循环的迭代。还可以在本章稍后讨论的其他类型循环中使用break和continue语句,它们还是以完全相同的方式工作。
|

|
| 图 3-4 循环中的break和continue语句 |
试一试:在循环中使用其他数据类型
迄今为止,我们仅仅使用过整数来记录循环的迭代次数。在使用何种变量类型来记录循环迭代次数方面,绝对不会受到任何限制。请看下面的示例:
- // Ex3_11.cpp
- // Display ASCII codes for alphabetic characters
- #include <iostream>
- #include <iomanip>
- using std::cout;
- using std::endl;
- using std::hex;
- using std::dec;
- using std::setw;
- int main()
- {
- for(char capital = 'A', small = 'a'; capital <= 'Z'; capital++, small++)
- cout << endl
- << "\t" << capital // Output capital as a character
- << hex << setw(10) << static_cast <int> (capital) // and as hexadecimal
- << dec << setw(10) << static_cast <int> (capital) // and as decimal
- << " " << small // Output small as a character
- << hex << setw(10) << static_cast <int> (small) // and as hexadecimal
- << dec << setw(10) << static_cast <int> (small); // and as decimal
- cout << endl;
- return 0;
- }