C语言中提供了可以随意滥用的 goto语句和标记跳转的标号。
从理论上 goto语句是没有必要的,实践中没有goto语句也可以很容易的写出代码。 但是某些场合下goto语句还是用得着的,最常见的用法就是终止程序在某些深度嵌套的结构的处理过 程。
例如:一次跳出两层或多层循环。 多层循环这种情况使用break是达不到目的的。它只能从最内层循环退出到上一层的循环。
(尽量少使用goto语句)
程序执行到goto时,会跳转到again出,故程序一直打印hehe,haha,陷入了死循环。
goto语句不能跨函数跳转,只能在本函数跳转。
goto语言真正适合的场景如下:
下面是使用goto语句的一个例子,然后使用循环的实现方式替换goto语句: 一个关机程序。
用while语句:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char input[20] = { 0 };
system("shutdown -s -t 60");
while (1)
{
printf("请注意,你的电脑在60秒内关机。如果输入我是猪,就取消关机\n");
scanf("%s", input);
if (strcmp(input, "我是猪") == 0)
{
system("shutdown -a");
break;
}
}
return 0;
}
用goto语句:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char input[20] = { 0 };
system("shutdown -s -t 60");
again:
printf("请注意,你的电脑在60秒内关机。如果输入我是猪,就取消关机\n");
scanf("%s", input);
if (strcmp(input, "我是猪") == 0)
{
system("shutdown -a");
}
else
{
goto again;
}
return 0;
}