在本教程中,您將學(xué)習(xí)在C語言編程中創(chuàng)建goto語句。此外,您還將學(xué)習(xí)何時(shí)使用goto語句以及何時(shí)不使用它。
goto語句使我們可以將程序的控制權(quán)轉(zhuǎn)移到指定的label 標(biāo)簽。
goto label; ... .. ... ... .. ... label: statement;
label是一個(gè)標(biāo)識(shí)符。goto遇到該語句時(shí),控制程序跳至label:并開始執(zhí)行代碼。
//程序計(jì)算正數(shù)的總和 //如果用戶輸入一個(gè)負(fù)數(shù),則顯示總和和平均值。 #include <stdio.h> int main() { const int maxInput = 100; int i; double number, average, sum = 0.0; for (i = 1; i <= maxInput; ++i) { printf("%d. 輸入數(shù)字: ", i); scanf("%lf", &number); //如果用戶輸入的是負(fù)數(shù),則跳轉(zhuǎn) if (number < 0.0) { goto jump; } sum += number; } jump: average = sum / (i - 1); printf("Sum(總和) = %.2f\n", sum); printf("Average(平均值) = %.2f", average); return 0; }
輸出結(jié)果
1. 輸入數(shù)字: 3 2. 輸入數(shù)字: 4.3 3. 輸入數(shù)字: 9.3 4. 輸入數(shù)字: -2.9 Sum(總和) = 16.60 Average(平均值) = 5.53
使用goto語句可能會(huì)導(dǎo)致代碼有錯(cuò)誤并且難以遵循。例如,
one: for (i = 0; i < number; ++i) { test += i; goto two; } two: if (test > 5) { goto three; } ... .. ...
此外,goto語句還允許您執(zhí)行不良操作,例如跳出范圍。
話雖如此,goto有時(shí)可能會(huì)有用。例如:打破嵌套循環(huán)。
如果您認(rèn)為使用goto語句可以簡化程序,則可以使用它。話雖如此,goto它很少有用,您也可以在不使用任何goto語句的情況下,創(chuàng)建任何C程序。
這是C ++的創(chuàng)建者Bjarne Stroustrup的話:“'goto'無所不能的事實(shí),正是我們不使用它的原因。”