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";热门推荐
10 新年祝福语大全简短感谢
11 祝女儿结婚简短祝福语
12 打麻将祝福语简短英文
13 广场周年庆祝福语 简短
14 学生国庆简短的祝福语
15 妈妈病人出院祝福语简短
16 简短的爱情生日祝福语
17 简短的祝福语中秋搞笑
18 父亲婚礼祝福语经典简短