goto语句也成为无条件转移语句
goto 语句标号
利用goto和if语句构成循环体,求1~100之和
main() { int i=1,sum=0; loop:sum+=i; i++; if(i<=100) goto loop; printf("%d",sum); }如非必要,建议不要使用goto...
goto要是在一个程序使用了很多次的时候必然使人眼花缭乱,但是有些场合,goto还是会显示出它的优势
void func() { for (int a = 0; a < 100; a++) { for (int b = 0; b < 100; a++) { for (int c = 0; c < 100; a++) { for (int d = 0; d < 100; a++) { for (int e = 0; e < 100; a++) { for (int f = 0; f < 100; a++) { for (int g = 0; g < 100; a++) { if (d == 50) { goto end; } } } } } } } } end:printf("d equals 50, stop all the loops!"); }建议多用break和continue,会起到同样作用
if (d == 50) { goto end; } 可以用if (d == 50) { break; }