C或C ++中的goto示例
goto语句是一个跳转语句,它允许程序控件从goto跳转到标签。人们不赞成使用goto语句,因为它会使程序复杂且难以理解。
以下是goto语句的语法。
goto label; . . . label: statements;
给出了一个用C++演示goto语句的程序,如下所示。
示例
#include <iostream>
using namespace std;
int main () {
int i = 1;
while(1) {
cout<< i <<"\n";
if(i == 10)
goto OUT;
i++;
}
OUT: cout<<"Out of the while loop";
return 0;
}输出结果
上面程序的输出如下。
1 2 3 4 5 6 7 8 9 10 Out of the while loop
现在,让我们了解以上程序。
在上面的程序中使用了while循环。在while循环的每一遍中,都会显示i的值。然后,如果使用if语句检查i的值是否为10。如果是,则使用goto语句退出while循环。否则,我将增加1。
goto语句使用的标签是OUT,它使程序控制退出while循环。然后显示“循环外”。给出的代码片段如下。
int i = 1;
while(1) {
cout<< i <<"\n";
if(i == 10)
goto OUT;
i++;
}
OUT: cout<<"Out of the while loop";热门推荐
2 训练狗狗成为
3 训练狗狗几岁
4 反应训练狗狗
5 听力训练狗狗
7 狗狗尿训练
8 拳击训练狗狗
10 狗狗训练卧室
11 一个月狗狗怎么训练
12 几个月训练狗狗大小便
13 牧羊犬训练狗狗
14 狗狗训练做
15 狗狗训练它
16 可以训练狗狗
17 训练狗狗给球
18 训练狗狗的技巧