'undeclared identifier'错误,即使变量是在代码中先前声明的

时间:2016-09-26 07:58:55

标签: c cs50

当用户输入值时,在第10行声明

int变量h

然而,当代码编译时,它表示未声明。

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    printf("How tall would you like your pyramid?\n");
    bool inc = true;
    while (inc)
    {
        int h = GetInt();
        if (h <= 23 && h >= 1)
        {
            inc = false;
        }
        else
        {
            printf("your value needs to be between 1 and 26\n");
        }
    }

    for (int i=0; i<=h; i++)
    {
        printf("#\n");
    }
}

1 个答案:

答案 0 :(得分:6)

您的变量h位于另一座城堡中:

while (inc)
{
    int h = GetInt();
    if (h <= 23 && h >= 1)
    {
        inc = false;
    }
    else
    {
        printf("your value needs to be between 1 and 26\n");
    }
    // h is destroyed after this line and is no longer visible.
}

for (int i=0; i<=h; i++)
{
    printf("#\n");
}

括号表示范围,范围表示可变可见性。 在h循环的范围内声明了whileh在该范围之外是不可见的,它在循环的}之外是不可见的。如果你想在循环之外访问它,你应该把它放在循环之外:

int h = -1;
while (inc)
{
    h = GetInt();
    if (h <= 23 && h >= 1)
    {
        inc = false;
    }
    else
    {
        printf("your value needs to be between 1 and 26\n");
    }
}

for (int i=0; i<=h; i++)
{
    printf("#\n");
}
// h is still visible here.