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

标签 c if-statement variables cs50 boolean-logic

我正在使用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/

相关文章:

mysql - #1064 使用 case for rand() 创建过程时出现语法错误

java - 如何测试 ArrayList<String> 中的某个项目是否位于某个位置

javascript - 如何从 html 文本框中获取输入并将其分配给 javascript 变量?

c++ - 如何在没有全局 Hook 的情况下获得鼠标/键盘事件的通知?

清除 double 的尾随 0?

c - 指针并置使得 int_pointer 指向字符数据,反之亦然

c - 对结构中的指针所指向的数组进行索引

sql - 如果字段 = Null,则使用不同的字段

bash - 期望:将生成命令的输出存储到变量中

variables - 以变​​量命名。 (通过AD林循环并计数服务器并生成报告)