声明遮蔽了 C 语言中的局部变量

declaration shadows a local variable in c

提问人:Fkhadim123 提问时间:9/23/2021 最后编辑:another.anon.cowardFkhadim123 更新时间:9/24/2021 访问量:8954

问:

我正在使用 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');
}
C if 语句 变量 CS50 布尔逻辑

评论

8赞 500 - Internal Server Error 9/23/2021
去掉第二行的前缀。有了它,你就重新声明了变量。charanswer
2赞 Nate Eldredge 9/23/2021
我们是否在 C 语言中的某个地方有一个关于变量阴影的规范问题,在初学者水平上解释它是什么以及如何避免错误地这样做?我以为我们必须这样做,但我找不到。
0赞 Fkhadim123 9/23/2021
谢谢!这解决了它

答:

0赞 Peter 9/23/2021 #1

尝试删除

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

因为它是在循环之外声明的

并将其启动为 char answer=“”;

评论

0赞 Peter 9/23/2021
根据上述评论
1赞 John Bollinger 9/23/2021
char answer声明 .该表达式表示字符串文本。后者很少是前者的合适初始值设定项。char""
1赞 Vlad from Moscow 9/23/2021 #2

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

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 循环之前隐藏同名变量的声明,而且该变量在循环外不活跃。

请注意,do-while 循环在 C 语言中按以下方式定义

do statement while ( expression ) ;

例如,您可以写

do ; while ( expression );

其中 do-while 语句的子语句是 null 语句。;

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

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

然后,此复合语句形成其一个作用域,并且所有具有自动存储持续时间的变量在复合语句之外都不是活动的。

也不要像这样调用 printf

printf("you are okay");

最好使用看跌期权的看涨期权,例如

puts("you are okay");

因为 put 的调用还附加了换行符的输出。'\n'

4赞 ryyker 9/23/2021 #3

请注意,您帖子中的警告消息非常有帮助。不要羞于简单地按照他们的建议一个接一个地遵循他们的建议。(它们是我用来提出以下建议的。

阴影是由块内部的第二个声明引起的:answerdo

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`

这里有一个关于变量阴影的 C 语言讨论,这里还有另一个更广泛的讨论