声明隐藏了 c 中的局部变量

declaration shadows a local variable in c

我正在使用 cs50 库和 ide,在尝试编译该程序时出现错误,提示变量 'answer' 已经声明,我不知道如何解决这个问题任何答案将不胜感激我真的坚持这个,因为我刚刚开始学习如何编程错误日志是:

char.c:9:14: error: declaration shadows a local variable [-Werror,-Wshadow]
        char answer = get_char("are you okay")

char.c:6:10: note: previous declaration is here
    char answer;

char.c:20:12: error: variable 'answer' is uninitialized when used here [-Werror,-Wuninitialized]
    while (answer != 'y' && answer != 'Y' && answer != 'n' && answer != 'N');

char.c:6:16: note: initialize the variable 'answer' to silence this warning
    char answer;

密码是:

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

int main(void)
{   
    char answer;
    do
    {
        char answer = get_char("are you okay Y/N ");
        if (answer == 'y' || answer == 'Y')
        {
            printf("you are okay");
        }
            else if (answer == 'n' || answer == 'N')
        {
            printf("you are not okay ");
        }

    }
    while (answer != 'y' && answer != 'Y' && answer != 'n' && answer != 'N');
}

尝试删除

中的字符

char answer = get_char("你还好吗Y/N");

因为它是在循环外声明的

并将其初始化为 char answer="";

在 do-while 循环的复合语句中,您需要使用在循环之前声明的相同变量 answer。

char answer;
do
{
    answer = get_char("are you okay Y/N ");
    if (answer == 'y' || answer == 'Y')
    {
        printf("you are okay");
    }
        else if (answer == 'n' || answer == 'N')
    {
        printf("you are not okay ");
    }

}
while (answer != 'y' && answer != 'Y' && answer != 'n' && answer != 'N');

否则在 do while 循环的复合语句中声明此声明

    char answer = get_char("are you okay Y/N ");

在while循环之前隐藏了同名变量的声明,而且这个变量在循环外是不存在的。

注意在C中do-while循环是这样定义的

do statement while ( expression ) ;

例如你可以写

do ; while ( expression );

其中 do-while 语句的子语句是空语句 ;

如果你使用复合语句作为子语句,如

do { /*...*/ } while ( expression );

则此复合语句形成其一个作用域,所有具有自动存储持续时间的变量在复合语句外均不存在。

也不要像这样调用 printf

printf("you are okay");

最好使用像

这样的看跌期权调用
puts("you are okay");

因为 puts 的调用还追加了换行符的输出 '\n'.

请注意,post 中的警告消息非常有用。不要羞于简单地逐一遵循他们的建议。 (它们是我用来提出以下建议的。)

阴影是由do块中answer的第二个声明引起的:

char answer;// original declaration (the shadow)
do
{
    char answer = get_char("are you okay Y/N ");//2nd declaration (being shadowed)

要修复,请执行此操作

char answer;// leave this declaration to allow proper scope
do
{
    answer = get_char("are you okay Y/N ");// uses same instance of 'answer' (no shadowing)
^^^^ removed second instance of `char`

variable shadowing here, and another more broad discussion here

上有针对 C 语言的讨论