next up previous contents
Next: nested switch statements Up: 判斷 Previous: switch statement   Contents

goto statement

  1. goto 可以讓程式直接跳到指定的標籤處,語法如下,標籤的位置在 goto 前(後)都可以。
    label_name:
        statement(s);
    .....
    
    goto label_name;
    
  2. 範例
    [dywang@dyw219 zzz]$ vim goto1.c
    [dywang@dyw219 zzz]$ cat goto1.c 
    #include <stdio.h>
    
    main() {
    	int i=0, a, sum=0;
    
    	printf("Enter an integer: ");
    	scanf("%d", &a);
    
    	add_start:
    	printf("%d", ++i );
    	sum += i;
    	if ( i<a ) {
    		printf("+");
    		goto add_start;
    	}
    	printf("=%d\n", sum );
    }
    
  3. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o goto1 goto1.c
    
  4. 執行結果
    [dywang@dyw219 zzz]$ ./goto1 
    Enter an integer: 10
    1+2+3+4+5+6+7+8+9+10=55
    [dywang@dyw219 zzz]$ ./goto1 
    Enter an integer: 7
    1+2+3+4+5+6+7=28
    



De-Yu Wang 2019-08-14