jeudi 23 septembre 2021

declaration shadows a local variable in c

I am using the cs50 library and ide and when trying to compile this program I get errors saying that the variable 'answer' has already been declared and I don't know how to solve this any answers would be appreciated I am really stuck on this as I have just began to learn how to program the error log is:

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;

The code is:

#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');
}

Aucun commentaire:

Enregistrer un commentaire