在C语言中,有一个很特殊的语法,这就是goto语句。goto用于实现同一函数的跳转,goto后面会有一个标志,执行goto语句时,就会跳转到标志的位置。
一、goto语句的语法
(1)goto在前,标志在后
没有使用goto语句的代码:
#include <stdio.h>int main()
{printf("C语言\n");printf("Java\n");printf("C++\n");return 0;
}
在VS2019中的运行结果:
上面的例子用于比较使用goto语句的情况:
上述代码使用了goto语句:
#include <stdio.h>int main()
{printf("C语言\n");printf("Java\n");goto flag;printf("C++\n");flag:return 0;
}
在VS2019中的运行结果:
在结果中,我们可以看到goto语句和标志间的代码并没有打印,也就是C++并没有打印在屏幕上。
(2)goto在后,标志在前
如果标志在前面,goto在后面会是怎样的情况呢?
参考代码:
#include <stdio.h>int main()
{printf("C语言\n");printf("Java\n");flag:printf("C++\n");goto flag;return 0;
}
在VS2019中的运行结果:
这时候我们可以看到,当执行到goto语句的时候又会返回到flag的位置,然后打印C++。后面又到goto,继而又到标志flag。从而,形成了一个死循环。
二、goto语句的应用场景
从刚刚的例子中,相信你学会了如何使用goto语句。goto语句用在函数中,跳转到标志的位置。如果使用次数过多,将会使得代码的可控性下降,不利于开发人员维护和阅读代码。但是,在多个循环中,使用goto语句可以很好的跳出多层循环。
之前的博客中提及到了多层循环是使用break跳出的,但是一个break只能跳出一层循环,当循环层数过多时使用break的数量也会变多。对于这种情况,我们可以使用goto语句很好解决。
参考代码:
#include <stdio.h>int main()
{int i = 0;int j = 0;int y = 0;for (i = 0; i < 10; i++){for (j = 0; j < 10; j++){for (y = 0; y < 10; y++){if (5 == y){printf("hehe\n");goto flag;}else {printf("hello\n");}}}}flag:return 0;
}
在VS2019中的运行结果:
我们可以看到,当满足判断条件时可以直接跳出多层循环。