当前位置: 首页 > 工具软件 > goto > 使用案例 >

C语言语句(3)——goto语句

岳风畔
2023-12-01

目录

1 介绍goto语句

2 写一个关机程序


1 介绍goto语句

C语言中提供了可以随意滥用的goto语句和标记跳转的标号,从理论上goto语句是没有必要的,实践中没有goto语句也可以很容易的写出代码,但是某些场合下goto语句还是用得着的,最常见的用法就是终止程序在某些深度嵌套的结构的处理过程。

goto语句和跳转标签必须在同一个函数里。例如:

代码展示:

#include <stdio.h>
int main()
{
again:
	printf("中国");
	printf("真美");
	goto again;
	return 0;
}

调试结果:死循环 打印中国真美

深层循环嵌套,调到循环外面需要多个break,但是仅仅使用一次goto语句就可以实现。

2 写一个关机程序

程序启动,60秒关机,如果60秒内 输入:不关机,就取消关机,如果不输入,就一直到关机为止。

代码展示:(用goto语句)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
	char input[20] = "";
	system("shutdown -s -t 60");
again:
	printf("提示,你的电脑在一分钟内关机,输入:不关机,就可以取消关机\n");
	scanf("%s", input);
	if (strcmp(input, "不关机") == 0)
	{
		system("shutdown -a");
	}
	else
	{
		goto again;
	}
	return 0;
}

知识点

(1)shutdown 是Windows提供的关机命令 -s设置关机 -t设置时间关机。 电脑上本来就具有,在电脑右下方搜索cmd——命令提示符,输入shutdown -s -t 60,就会开始60秒倒计时关机。( shutdown -s -t 60(关机命令)shutdown -a(解除关机命令))

(2)system() 是一个库函数,专门用来执行系统命令,头文件是<stdlib.h>

(3)strcmp()函数,在C语言语句(2)——循环语句中有讲到,友友们可以查找一下。

代码展示:(不用goto语句)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
	char input[20] = "";
	system("shutdown -s -t 60");
	while (1)
	{
		printf("提示,你的电脑在一分钟内关机,输入:不关机,就可以取消关机\n");
		scanf("%s", input);
		if (strcmp(input, "不关机") == 0)
		{
			system("shutdown -a");
		}
		else
		{
			break;
		}
	}
	return 0;
}

C语言语句版块的介绍就到此结束了。

希望友友们可以提出宝贵的意见。

 类似资料: