goto語(yǔ)句被稱為C語(yǔ)言中的跳轉(zhuǎn)語(yǔ)句。用于無(wú)條件跳轉(zhuǎn)到其他標(biāo)簽。它將控制權(quán)轉(zhuǎn)移到程序的其他部分。
goto語(yǔ)句一般很少使用,因?yàn)樗钩绦虻目勺x性和復(fù)雜性變得更差。
語(yǔ)法
goto label;
讓我們來(lái)看一個(gè)簡(jiǎn)單的例子,演示如何使用C語(yǔ)言中的goto語(yǔ)句。
打開(kāi)Visual Studio創(chuàng)建一個(gè)名稱為:goto的工程,并在這個(gè)工程中創(chuàng)建一個(gè)源文件:goto-statment.c,其代碼如下所示 -
#include <stdio.h>
void main() {
int age;
gotolabel:
printf("You are not eligible to vote!\n");
printf("Enter you age:\n");
scanf("%d", &age);
if (age < 18) {
goto gotolabel;
}else {
printf("You are eligible to vote!\n");
}
}
執(zhí)行上面代碼,得到以下結(jié)果 -
You are not eligible to vote!
Enter you age:
12
You are not eligible to vote!
Enter you age:
18
You are eligible to vote!