int main(void) {
int start;
start = get_int(); // 呼叫尚未定義的函式
int get_int(void) { // 函式定義在 main 內部且位於呼叫之後
// ...
}
system("pause");
}
編譯器報錯:error C2143: 語法錯誤。
get_int 定義在 main 內部且在呼叫語句之後,編譯器掃描到呼叫時尚未看到宣告,導致語法分析失敗。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 標頭檔。.c 檔,建議專案屬性 → C/C++ → Advanced → Compile As: Compile as C Code (/TC)。將函式定義移出 main 並加上前向宣告,即可消除 C2143 錯誤。遵循標準 C 程式結構,程式碼更清晰、可移植。