gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:16:12 26 4
gpt4 key购买 nike

我正在使用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');
}

最佳答案

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

阴影是由 do block 内 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 有一个针对 C 的讨论,还有更多 broad discussion here

关于c - 声明隐藏了 c 中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69302363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com