文章目录
C语言中提供了可以随意滥用的goto语句和标记跳转的标号。
理论上goto语句是没有必要的,实践中没有goto语句也可以很容易的写出代码。
但是某些场合下goto语句还是用得着的,最常见的用法就是终止程序在某些深度嵌套的结构的处理过程中,例如一次跳出两层过多层循环。
这种情况下使用break是达不到目的的。它只能从最内层循环退出到上一层的循环。
一、标记跳转的标号
(1)标号的名字可以随意取
#include<stdio.h>
int main()
{
end: //end 这个名字是自己随意取的,可以是sunchao 等等,都可以
printf("haha\n");
goto end;
return 0;
}
(2)标号可以在goto语句的前面或者后面
#include<stdio.h>
int main()
{
qp:
printf("haha\n");
goto sunchao;
sunchao:
printf("hehe\n");
goto qp;
return 0;
}
二、goto语句
(1)只能在一个函数范围内跳转,不能跨函数。
//goto 语句只能在函数内部跳转,不能够跨函数
#include <stdio.h>
void test()
{
flag: //goto不可以跨函数,这样子是运行不了的
printf("haha\n");
}
int main()
{
printf("test\n"); //goto不可以跨函数,这样子是运行不了的
goto flag;
return 0;
}
三、一个关机程序
方法(1)goto 语句
#include <stdio.h>
#include <stdlib.h> //system("shutdown -t -s")
#include <string.h>
int main()
{
char input[20] = {0};
system("shutdown -s -t 600");//电脑将在600秒后关机
again:
printf("请输入“我是猪”,否则电脑将在600秒后关机\n");
scanf("%s", input); //由于input 是数组,所以不要加上 取地址运算符&
if (strcmp(input, "我是猪") == 0)
{
system("shutdown -a");
}
else
{
goto again;
}
return 0;
}
方法(2)使用循环实现
#include <stdio.h>
#include <stdlib.h> //system("shutdown -t -s")
#include <string.h>
int main()
{
char input[20] = {0};
system("shutdown -s -t 600");
while (1)
{
printf("请输入“我是猪”,否则电脑将在600秒后关机\n");
scanf("%s", input);
if (strcmp(input, "我是猪") == 0)
{
system("shutdown -a");
break;
}
}
return 0;
}
c
微软雅黑字体
黑体
3号字
4号字
红色
绿色
蓝色