编译器错误变量声明

时间:2017-02-03 19:11:18

标签: c variables

我收到一个奇怪的错误,说我的变量没有被声明,即使我已经在main中声明了它们。我错过了什么吗?

  

错误4错误C2065:'目的地':未声明的标识符c:\ users \ owner \ documents \ visual studio 2012 \ projects \ project36 \ project36 \ source.c 26 1 Project36

我在C编程。

变量声明:

char sourcePiece;
char destination;

函数调用:

askForMove(sourcePiece, destination);

功能def:

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 );

4 个答案:

答案 0 :(得分:2)

正如一些评论者所指出的,其中一个问题是您不能拥有本地变量和具有相同名称的形式参数。我建议您删除局部变量的声明,因为它是您要在函数中使用的参数,而不是它们。

答案 1 :(得分: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

<强>更新 AnT的说法有意义,请参阅此C89, Mixing Variable Declarations and Code

答案 2 :(得分:1)

代码的完整版本和带有错误的最新屏幕截图表明编译器抱怨main函数中的局部变量声明。编译器抱怨,因为变量声明与main内的语句交错,而#34; classic&#34; C语言(C89 / 90)。要编译此代码,您需要一个C99(或更高版本)编译器。

代码很容易为C99之前的编译器修复 - 只需将所有局部变量声明移到封闭块的开头(即在你的情况下到main的开头)。

答案 3 :(得分:0)

我不确定您打算在您的程序中实现什么,但您的变量名称中有重复项。不要对函数参数和局部变量使用相同的名称。