C语言:goto循环语句


goto语句构成循环
在介绍C语言的循环结构之前,先介绍一种采用非结构化程序设计的方式来构成的循环,即使用无条件转移语句goto语句。
它的一般格式如下:
goto语句标号:

说明: goto语句把程序的控制流转移到在goto语句中指定的标号之后的第一条语句。
 标号是跟有“:”的标识符,它必须与引用它的goto语句在同一个函数中,但可以不在同一个循环层中。标号的命名规则与变量名相同,即由字母、数字和下画线组成,其第一个字符必须为字母或下商线,不能用整数来做标号。


例如: goto lsx;是正确的,而goto 12;是错误的。

例:编写程序:求10个学生的总成绩。
分析:该题显然是在重复做累加求和的工作,关键是怎样控制循环的停止。
可以借助前面学过的if语句和goto语句一起来构成循环。

#include<stdio.h>
void main()
{
    int count=1,total=0,grade;
    star: if(count<=10)
    {
        printf("input the grade:");
        scanf("%d",&grade);
        total = total+grade;
        count++;
        goto star;
    }
    printf("total=%d\n",total);
}

运行结果:

input the grade:98
input the grade:99
input the grade:97
input the grade:93
input the grade:92
input the grade:90
input the grade:88
input the grade:78
input the grade:79
input the grade:91
total=905

在编写程序时建议使用结构化设计,一般不提倡使用非结构化goto语句(除非它能够极大地提高效率),因为如果滥用了这种语句将使程序难以调试,维护和修改。

猜你喜欢

转载自blog.csdn.net/weixin_44015669/article/details/89366524