日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

C語(yǔ)言goto語(yǔ)句簡(jiǎn)單使用詳解_C 語(yǔ)言

作者:Josvin ? 更新時(shí)間: 2022-03-26 編程語(yǔ)言

簡(jiǎn)單介紹

C語(yǔ)言中提供了可以隨意濫用的 goto語(yǔ)句和標(biāo)記跳轉(zhuǎn)的標(biāo)號(hào)。
從理論上 goto語(yǔ)句是沒(méi)有必要的,實(shí)踐中沒(méi)有g(shù)oto語(yǔ)句也可以很容易的寫出代碼。
但是某些場(chǎng)合下goto語(yǔ)句還是用得著的,最常見(jiàn)的用法就是終止程序在某些深度嵌套的結(jié)構(gòu)的處理過(guò)程,例如一次跳出兩層或多層循環(huán)。
這種情況使用break是達(dá)不到目的的。它只能從最內(nèi)層循環(huán)退出到上一層的循環(huán)。

語(yǔ)法

C 語(yǔ)言中 goto 語(yǔ)句的語(yǔ)法:

goto label;
..
.
label: statement;

示例對(duì)比

#include<stdio.h>

int main() {
	int c = 1;
	if (c) {
		goto start;
	}

start:
	printf("實(shí)例1\n");
	printf("實(shí)例2\n");
	printf("實(shí)例3\n");
	printf("實(shí)例4\n");
	printf("實(shí)例5\n");
}

輸出結(jié)果:

在這里插入圖片描述

#include<stdio.h>

int main() {
	int c = 1;
	if (c) {
		goto start;
	}


	printf("實(shí)例1\n");
	printf("實(shí)例2\n");
	printf("實(shí)例3\n");
start:	
	printf("實(shí)例4\n");
	printf("實(shí)例5\n");
}

輸出結(jié)果:

在這里插入圖片描述

下面是使用goto語(yǔ)句的一個(gè)例子:

關(guān)機(jī)程序

#include <stdio.h>
int main()
{
  char input[10] = {0};
  system("shutdown -s -t 60");
again:
  printf("電腦將在1分鐘內(nèi)關(guān)機(jī),如果輸入:我是豬,就取消關(guān)機(jī)!\n請(qǐng)輸入:>");
  scanf("%s", input);
  if(0 == strcmp(input, "我是豬"))
 {
    system("shutdown -a");
 }
 else
 {
    goto again;
 }
  return 0;
  }

而如果不適用goto語(yǔ)句,則可以使用循環(huán):

#include <stdio.h>
#include <stdlib.h>
int main()
{
  char input[10] = {0};
  system("shutdown -s -t 60");
  while(1)
 {
    printf("電腦將在1分鐘內(nèi)關(guān)機(jī),如果輸入:我是豬,就取消關(guān)機(jī)!\n請(qǐng)輸入:>");
    scanf("%s", input);
    if(0 == strcmp(input, "我是豬"))
   {
      system("shutdown -a");
      break;
   }
 }
  return 0;
}

goto語(yǔ)言真正適合的場(chǎng)景如下:

for(...)
  for(...)
 {
    for(...)
   {
      if(disaster)
        goto error;
   }
 }
  …
error:
if(disaster)
    // 處理錯(cuò)誤情況

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

原文鏈接:https://blog.csdn.net/weixin_45532227/article/details/109126018

欄目分類
最近更新