c/c++语言开发共享C语言goto语句简单使用详解

简单介绍c语言中提供了可以随意滥用的 goto语句和标记跳转的标号。从理论上 goto语句是没有必要的,实践中没有goto语句也可以很容易的写出代码。但是某些场合下goto语句还是用得着的,最常见的用


简单介绍

c语言中提供了可以随意滥用的 goto语句和标记跳转的标号。
从理论上 goto语句是没有必要的,实践中没有goto语句也可以很容易的写出代码。
但是某些场合下goto语句还是用得着的,最常见的用法就是终止程序在某些深度嵌套的结构的处理过程,例如一次跳出两层或多层循环。
这种情况使用break是达不到目的的。它只能从最内层循环退出到上一层的循环。

语法

c 语言中 goto 语句的语法:

goto label;  ..  .  label: statement;

示例对比

#include<stdio.h>    int main() {  	int c = 1;  	if (c) {  		goto start;  	}    start:  	printf("实例1n");  	printf("实例2n");  	printf("实例3n");  	printf("实例4n");  	printf("实例5n");  }  

输出结果:

C语言goto语句简单使用详解

#include<stdio.h>    int main() {  	int c = 1;  	if (c) {  		goto start;  	}      	printf("实例1n");  	printf("实例2n");  	printf("实例3n");  start:	  	printf("实例4n");  	printf("实例5n");  }  

输出结果:

C语言goto语句简单使用详解

下面是使用goto语句的一个例子:

关机程序

#include <stdio.h>  int main()  {    char input[10] = {0};    system("shutdown -s -t 60");  again:    printf("电脑将在1分钟内关机,如果输入:我是猪,就取消关机!n请输入:>");    scanf("%s", input);    if(0 == strcmp(input, "我是猪"))   {      system("shutdown -a");   }   else   {      goto again;   }    return 0;    }  

而如果不适用goto语句,则可以使用循环:

#include <stdio.h>  #include <stdlib.h>  int main()  {    char input[10] = {0};    system("shutdown -s -t 60");    while(1)   {      printf("电脑将在1分钟内关机,如果输入:我是猪,就取消关机!n请输入:>");      scanf("%s", input);      if(0 == strcmp(input, "我是猪"))     {        system("shutdown -a");        break;     }   }    return 0;  }  

goto语言真正适合的场景如下:

for(...)    for(...)   {      for(...)     {        if(disaster)          goto error;     }   }    …  error:  if(disaster)      // 处理错误情况  

在这里可以代替多次 break 的跳出

到此这篇关于c语言goto语句简单使用详解的文章就介绍到这了,更多相关c语言goto语句使用内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!

需要了解更多c/c++开发分享C语言goto语句简单使用详解,都可以关注C/C++技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/1038157.html

(0)
上一篇 2022年1月26日
下一篇 2022年1月26日

精彩推荐