4.3.1 break、coninue、goto
关键词 | 意义 |
---|---|
break | 立即跳出循环 |
continue | 结束本次循环结束,直接进行下一轮循环 |
goto | 跳到其他标识的地方 |
1.break演示:
#include<iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 9; i++)
{
cout << i << endl;
for (int j = 1; j <= 10; j++)
{
if (j == 6)
{
break;
}
cout << j << '\t';
}
cout << endl;
}
system("pause");
return 0;
}
运行结果:
可以看到,j每次只打印到5就结束了循环,但只是结束了内层循环,外层继续运行,不受影响。
2.continue演示:
同样还是上面的代码,将break换成continue。
#include<iostream>
using namespace std;
int main()
{
//乘法口诀表
for (int i = 1; i <= 9; i++)
{
cout << i << endl;
for (int j = 1; j <= 10; j++)
{
if (j == 6)
{
continue;
}
cout << j << '\t';
}
cout << endl;
}
system("pause");
return 0;
}
运行结果:
可以看到,内层循环跳过了6,继续打印后面的数。
3.goto演示:
#include<iostream>
using namespace std;
int main()
{
//goto语句
cout << "1、xxx" << endl;
cout << "2、xxx" << endl;
goto FLAG;
cout << "3、xxx" << endl;
cout << "4、xxx" << endl;
FLAG:
cout << "5、xxx" << endl;
system("pause");
return 0;
}
运行结果:
可以看到,运行到goto语句时,程序直接跳转到FLAG标识的地方。