C语言的goto语句提供无条件跳转,与标记语句的功能是相同的。
注意:goto语句强烈不鼓励使用在任何编程语言,因为它使得难以跟踪程序的控制流程,使程序难以理解,难以修改。使用goto语句使任何程序可以改写,以便它不需要goto语句。
在C语言中 goto语句的语法如下:
goto label; .. . label: statement;
在这里,标签(label)是除了C语言关键字外的任何纯文本,它可以在在C程序任何地方设置(上方或下方)goto语句。
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d", a);
a++;
}while( a < 20 );
return 0;
}
当上述代码被编译和执行时,它产生了以下结果:
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19