在 C 内部控制部分声明变量时出现编译时错误

标签 c gcc syntax c99

我正在尝试编译一个程序(来自 Stephen Prata 的 C Primer Plus 第 6 版的 list 12.13 - Manydice.c),但收到编译错误:“状态”未声明(在此函数中首次使用)。

如果您能对“在任何地方声明”的 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

为什么我会收到此错误?

最佳答案

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

其次,“声明”并不等同于“首次出现”。标识符的声明至少将类型信息与该标识符相关联,并且其位置确定了标识符的范围。如果没有声明(如您的情况),则不存在可以使用标识符的范围。 Primordial C 对此有更宽松的规则,但由于您似乎想依赖 C99,所以这些规则是无关紧要的。

变量status最简单的声明如下:

int status;

这需要在第一次使用该变量之前出现,并且其范围延伸到最内层封闭 block 的末尾,或者如果它出现在任何 block 之外,则延伸到文件的末尾。然而,就你而言,我可能只会替换

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

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

         if (status != 1)

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

关于在 C 内部控制部分声明变量时出现编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228070/

相关文章:

c - 如何使用mosquitto_publish同步发布数据?

c - C 中的 long long 乘法给出错误的结果

php - PHP语法错误: Unexpected ']' [closed]

c - 抛出总线错误,不明白为什么

python - 使用 Cython 和 "next"编译

c - 从c中的命令行读取的字符串中打印转义字符

gcc,不同架构上 long int 的宽度

c++ - 当 std::uint_fast32_t 在 GCC 中为 4 字节时,std::mt19937 失败

syntax - 为什么 "||"是 or 的符号?

Javascript 变量声明,初始化变量用括号括起来