首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

VS2013 編譯 C Primer Plus 範例報錯 C2143:函式定義順序導致的語法錯誤

     編輯:程式設計綜合問答

錯誤代碼片段

int main(void) {
    int start;
    start = get_int(); // 呼叫尚未定義的函式
    int get_int(void) { // 函式定義在 main 內部且位於呼叫之後
        // ...
    }
    system("pause");
}

編譯器報錯:error C2143: 語法錯誤。

錯誤原因

  • C/C++ 要求函式必須在使用前宣告或定義。
  • 範例中 get_int 定義在 main 內部且在呼叫語句之後,編譯器掃描到呼叫時尚未看到宣告,導致語法分析失敗。
  • C 標準不允許巢狀函式定義(GCC 支援為擴充),Visual Studio 更不支援。

修正方法

  1. 將 get_int 移至 main 外部,並在 main 前加上前向宣告:
#include <stdio.h>
#include <stdlib.h>

int get_int(void); // 前向宣告

int get_int(void) {
    int input, ch;
    while (scanf("%d", &input) != 1) {
        while ((ch = getchar()) != '\n') putchar(ch);
        printf("is not an integer.\nPlease enter an integer value, such as 25, 178 or 3: ");
    }
    return input;
}

int main(void) {
    int start = get_int();
    printf("You entered: %d\n", start);
    system("pause");
    return 0;
}

最佳實踐

  • 所有自訂函式統一放在 main 之前,或寫在獨立 .c 檔並建立 .h 標頭檔。
  • 養成「先宣告,後使用」的習慣,避免巢狀函式。
  • VS2013 預設以 C++ 模式編譯 .c 檔,建議專案屬性 → C/C++ → Advanced → Compile As: Compile as C Code (/TC)。

總結

將函式定義移出 main 並加上前向宣告,即可消除 C2143 錯誤。遵循標準 C 程式結構,程式碼更清晰、可移植。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved