1. 程式人生 > 其它 >C語言中使用goto語句

C語言中使用goto語句

技術標籤:C++

goto語法規則:goto和標籤名,比如:gotoaa;,aa是標籤名。

先看例子,程式碼如下:

#include <stdio.h>
int main(void){

    int a=2,b=3;

    if(a<b){
    goto aa;
    }
    
    printf("hello\n");

    aa:printf("s\n");

    return 0;

}

列印結果:

在這可以看到當滿足if條件時goto aa是直接跳轉到了aa:printf(“s”),緊接著走return語句,並不會返回if方法然後走printf(“hello”)

反之如果程式碼像下面這樣,goto aa將沒有任何意義

#include <stdio.h>
int main(void){

    int a=2,b=3;

    if(a>b){
    goto aa;
    }
    
    printf("hello\n");

    aa:printf("s\n");

    return 0;

}

列印結果:

當if條件不滿足時,雖然執行了aa:printf("s\n")語句,但這裡和aa並沒有關係,只是和printf()語句有所關聯