【问题标题】:Compile time error when declaring variables in C inside control section在控制部分内的 C 中声明变量时出现编译时错误
【发布时间】:2017-05-04 19:52:45
【问题描述】:

我正在尝试编译一个程序(清单 12.13 - 来自 Stephen Prata 的 C Primer Plus 6th Edition 的 manydice.c),但出现编译错误:'status' undeclared(首次在此函数中使用)。

我也将感谢有关“在任何地方声明”的 c99 标准的澄清。

下面是部分代码:

int main(void)
{
    int dice, roll;
    int sides;

    srand((unsigned int) time(0));       /* randomize seed       */
    printf("Enter the number of sides per die, 0 to stop.\n");
    while(scanf("%d", &sides) == 1 && sides > 0)
    {
        printf("How many dice?\n");
        if((status = scanf("%d", &dice)) != 1)
        {
            if(status == EOF)
            {
                break;                  /* exit loop            */
            }
            ...

错误信息是:

||=== Build: Debug in dice (compiler: GNU GCC Compiler) ===|
~manydice.c||In function 'main':|
~manydice.c|19|error: 'status' undeclared (first use in this function)|
~manydice.c|19|note: each undeclared identifier is reported only once for each function it appears in|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

选项:(使用 code::blocks 16.01 mingw 32bit --gcc 版本显示 gcc 4.9.2,Windows 7 Ultimate 32 位)

 mingw32-gcc.exe -Wall -g -std=c99  -c

为什么会出现这个错误?

【问题讨论】:

  • 因为你还没有定义你正在使用的变量status
  • 您的代码中没有任何内容看起来像是在尝试声明 status。你认为它是在哪里声明的?
  • @Wumpus Q. Wumbley 就像我说的正在学习,正在从上述书中学习这个示例(我输入的内容与书中完全相同),它不会编译,我不知道出了什么问题所以我提出了这个问题。如果您向我解释错误而不是指出更多我不知道的错误,那会更有帮助
  • for(i = 0; i < 5; i++) 不应该工作。 for(int i = 0; i < 5; i++) 是正确的选择。
  • 作为参考,the book's published code 有点不同。

标签: c gcc syntax c99


【解决方案1】:

你的期望(或理解)是错误的。

引用章节§6.8.4.1,C11if 语句的语法是

if ( 表达式 ) 声明

而且,变量声明不是表达式声明

但是,您可以在 statement 部分中定义一个变量。

【讨论】:

    【解决方案2】:

    首先,您声称在 C“控制部分”中允许变量声明,其中显然包括 if 语句的条件。你误会了。从 C99 开始,允许声明代替 for 循环的控制子句中的第一个表达式,但 not 代替其他流程中的控制表达式 -控制结构,例如ifwhile 语句。

    其次,“声明”不是“首次出现”的同义词。标识符的声明至少将类型信息与该标识符相关联,其位置确定了标识符的范围。如果有 no 声明 - 就像你的情况一样 - 那么有 no 可以使用标识符的范围。 Primordial C 对此有更宽松的规则,但既然您似乎想依赖 C99,这些都无关紧要。

    变量status 的最简单声明是这样的:

    int status;
    

    这需要在第一次使用该变量之前出现,并且它的范围扩展到最里面的封闭块的末尾,或者如果它出现在任何块之外,则扩展到文件的末尾。但是,在您的情况下,我可能只是替换

            if((status = scanf("%d", &dice)) != 1)
    

             int status = scanf("%d", &dice);
    
             if (status != 1)
    

    这两者都声明status 并为其计算一个初始值,然后您可以使用它。我发现这比在同一个表达式中执行值计算和测试更清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多