【问题标题】:Compiler error variable declaration编译器错误变量声明
【发布时间】:2017-02-04 04:02:25
【问题描述】:

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

错误 4 错误 C2065:'destination':未声明的标识符 c:\users\owner\documents\visual studio 2012\projects\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 );

【问题讨论】:

  • 你能显示整个代码吗?
  • 你不是在函数中复制char源和目标吗?
  • 我认为参数名称并不重要。他们是不同的,不是吗?是的,我可以发布整个代码。
  • 你在读你写的代码吗?您同时在范围内有两个 char SourcePiece 变量(您作为参数接收到 askForMove 的一个变量和一个您在 askForMove 内声明的新变量)。
  • 问题描述不准确。 askForMove 的代码无效(正如上面的 cmets 中已经解释的那样),但引用的错误消息甚至与 askForMove 中的错误不匹配。触发引用错误消息的第 26 行代码在哪里?

标签: c variables


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    完整版本的代码和您发布的带有错误的最新屏幕截图表明编译器抱怨在 main 函数中进行的局部变量声明。编译器抱怨,因为变量声明与 main 中的语句交错,“经典”C 语言 (C89/90) 不支持。为了编译此代码,您需要 C99(或更高版本)编译器。

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

    【讨论】:

    • @Shinji-san 总是发布可验证的代码,以及有错误的行,这对于努力解决您的问题的人来说很容易:)。
    • 先生,我需要和你谈谈,我们可以聊聊吗?
    【解决方案3】:

    你应该知道

    形式参数,在函数中被视为局部变量。

    所以你在这里复制它们并导致错误。

     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

    【讨论】:

    • 谢谢。但它现在甚至阻止我为这些参数分配任何东西。语句 'x = 4' 正在产生错误。void askForMove( char x, char y ) { x = 4 } 正在产生错误。
    • 4 是整数,char 不是,如果要存储符号 4,请使用 x = '4';
    • @Shinji-san:你在编造东西。 x = 4 除了末尾缺少分号外没有任何问题(修改参数不会影响实际参数)。
    • @AnT 是 char ,不应该是 char x = '4'
    • 这不是假报价,我不会那样做。我不知道是怎么回事。当我发布这个问题时,我只是复制了显示的错误。我只是想弄清楚编译器出了什么问题。但绝对不是假的。如果您愿意,我可以再为错误截屏。
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 2019-02-02
      • 2011-01-11
      • 2012-10-23
      相关资源
      最近更新 更多