2017-02-03 114 views
0

我得到一個奇怪的錯誤,說我的變量沒有被聲明,即使我已經在main中聲明瞭它們。我錯過了什麼嗎?編譯器錯誤變量聲明

錯誤4錯誤C2065:目的地:未聲明的標識符C:\用戶\所有者\文件\視覺工作室2012 \項目\ project36 \ project36 \由source.c 26 1 Project36

我編程C.

變量聲明:

char sourcePiece; 
char destination; 

函數調用:

askForMove(sourcePiece, destination); 

功能高清:

void askForMove(char sourcePiece, char destination) { 
    char sourcePiece; 
    char destination; 
    printf("\nEnter your desired move. First enter the starting position, followed by the ending position in letters: "); 
    scanf(" %c %c", &sourcePiece, &destination); 

} 

原型:

void askForMove(char, char); 
+1

你能顯示整個代碼嗎? –

+3

是不是你複製char sourcepiece和函數中的目的地。 –

+0

我認爲參數名稱並不重要。他們是不同的,不是嗎?是的,我可以發佈整個代碼。 –

回答

1

全面和版本的代碼與您發佈錯誤的最新截圖表明,編譯器抱怨中所作的局部變量聲明main功能。編譯器會抱怨,因爲變量聲明與main內部的語句交錯,而「經典」C語言(C89/90)不支持該語句。爲了編譯此代碼,您需要一個C99(或更高版本)編譯器。

對於C99之前的編譯器,該代碼很容易修復 - 只需將所有局部變量聲明移至封閉塊的開頭(即在您的案例中爲main的開頭)。

+0

啊,有效的,謝謝!!! –

+0

@ Shinji-san總是發佈可驗證的代碼和有錯誤的代碼,對於這個人來說很容易努力解決你的問題:) –

+0

先生,我需要和你談談,我們可以聊天嗎? –

2

因爲它已經被一些評論者指出,其中一個問題是,你不能有一個局部變量和一個正式的參數同名。我建議你刪除局部變量的聲明,因爲它是你想在你的函數中使用的參數,而不是它們。

0

我不確定你想在你的程序中實現什麼,但是你的變量名有重複。不要爲函數參數和局部變量使用相同的名稱。

1

你應該知道,

形式參數,作爲一個函數內的局部變量處理。

所以在這裏您正在複製它們並導致錯誤。

void askForMove(char sourcePiece, char destination) { 
char sourcePiece; //Redeclaring already present in formal parameter. 
char destination; //Redeclaring already present in formal parameter. 
printf("\nEnter your desired move. First enter the starting position, followed by the ending position in letters: "); 
scanf(" %c %c", &sourcePiece, &destination); 

} 

刪除他們

void askForMove(char sourcePiece, char destination) { 
printf("\nEnter your desired move. First enter the starting position, followed by the ending position in letters: "); 
scanf(" %c %c", &sourcePiece, &destination); 

} 

也注意到你的問題不是一天應該怎麼寫一個很好的例子,始終郵政Minimal, Complete, and Verifiable example

更新 什麼螞蟻說是有意義的,看到這個C89, Mixing Variable Declarations and Code

+0

謝謝。但它現在阻止了我爲這些參數分配任何東西。語句'x = 4'正在生成errors.void askForMove(char x,char y){x = 4}正在產生錯誤。 –

+0

@ Shinji-san CAn請給我看整個代碼? –

+0

4是整數,char不是,如果你想存儲符號4,使用x ='4'; –