C/C++中的跳转语句:breakcontinuegoto

Posted Shemesz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C/C++中的跳转语句:breakcontinuegoto相关的知识,希望对你有一定的参考价值。

(1)break语句

作用:用于跳出选择结构或者循环结构

break使用的时机

  • 出现在switch条件语句中,作用是终止case并且跳出switch;
  • 出现在循环语句中,作用是跳出当前的循环语句;
  • 出现在嵌套循环中,作用是跳出最近的内层循环语句;

示例1

#include <iostream>
using namespace std;

int main()
{
	//1.出现在switch语句当中
	cout << "请选择难度" << endl;
	cout << "普通" << endl;
	cout << "中等" << endl;
	cout << "困难" << endl;
	
	int select = 0; //创建选择结果的变量

	cin >> select;

	switch (select)
    {
	case 1:
		cout << "您选择的是普通难度" << endl;
		break;
	case 2:
		cout << "您选择的是中等难度" << endl;
		break;
	case 3:
		cout << "您选择的是困难难度" << endl;
		break;
	default:
		break;
	}
    system("pause");

	return 0;
}

在这里插入图片描述
示例二

#include <iostream>
using namespace std;

int main()
{
	//2.出现在循环语句当中
	for (int i = 0; i < 10; i++)
	{
		//如果i=5就退出循环
		if (i == 5)
		{
			break;
		}
		cout << i << endl;
	}

	system("pause");

	return 0;
}

在这里插入图片描述
示例三

#include <iostream>
using namespace std;

int main()
{
	//3.出现在嵌套循环语句当中
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			cout << "*";
		}
		cout << endl;
	}

	system("pause");

	return 0;
}

没有加break语句的效果
在这里插入图片描述
再加上break

#include <iostream>
using namespace std;

int main()
{
	//3.出现在嵌套循环语句当中
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			if (j == 5)
			{
				break;  //推出内层循环
			}
			cout << "*";
		}
	
		cout << endl;
	}

	system("pause");

	return 0;
}

少了一半的 ’ * ’
在这里插入图片描述

(2)continue语句

作用:在循环语句中,跳过本次循环中余下尚未执行的语句,继续执行 下一次循环。
示例

#include <iostream>
using namespace std;

int main()
{
	for (int i = 0; i < 100; i++)
	{
		//如果是奇数就输出,偶数就不输出
		if (i % 2 == 0)
		{
			continue;  //可以作为筛选条件,执行到这里就不再向下执行,执行下一次循环
		}
		cout << i << endl;

	}
	system("pause");

	return 0;
}

在这里插入图片描述
注意:continue并没有使循环终止,而break会跳出循环。

(3)goto语句

作用:可以无条件跳转语句

语法goto 标记语句
解释:如果标记的名称存在,则goto语句就会跳转到标记的位置

示例

#include <iostream>
using namespace std;

int main()
{
	cout << 1 << endl;
	cout << 2 << endl;
	goto FLAG;

	cout << 3 << endl;
	cout << 4 << endl;

	FLAG:
	cout << 5 << endl;

	system("pause");

	return 0;
}

在这里插入图片描述
在2后面使用跳转,在跳转标记后执行语句,goto跳转语句一般用来处理程序出错后的清理语句;
注意:在程序中不建议使用goto语句,以免造成程序混乱

以上是关于C/C++中的跳转语句:breakcontinuegoto的主要内容,如果未能解决你的问题,请参考以下文章

web中的跳转语句 java中的跳转语句

c#网页之间的跳转语句

C语言关于SWITCH语句的跳转问题

关于breakcontinue和return

00016_跳转语句break

2.7.3与程序转移有关的跳转语句