0

I want to test how the do-while loop works. But I encounter a problem, which I've spent an hour working on but couldn't figure out a solution. Here's my code.

int main(void)
{
    int n;
    do
    {
        // n = get_int("Please type in an integer here: ");
    }
    while ( n < 0 || n > 23);
    {
        printf("%i\n", n);
    }
}

My aim is to let users type in an integer, and then check if it fits in the rule. If it does, then print it on the screen. But the system constantly reminds me:

mario.c:11:13: error: variable 'n' is uninitialized when used here [-Werror,-Wuninitialized] while ( n < 0 || n > 23); ^ mario.c:6:10: note: initialize the variable 'n' to silence this warning int n; ^ = 0 1 error generated.

It seems to be asking me to initialize the "n" in the while(). But I suppose I've done this in the very beginning. Could you help me find out where goes wrong? :)

1

By this you declared (but did not initialize) the variable:

  int n;

The following is recognized as a comment but not an initialization because of "//":

// n = get_int("Please type in an integer here: ");

So you can simply delete "//" and after that the variable will be initialized:

n = get_int("Please type in an integer here: ");
1

The message is clear, you must learn to interpret it as a programmer since it is almost impossible to write a program free of errors at the first attempt. If you look at the first time that the variable n is declared is not initialized, the solution is simple and your program should be like this:

int main(void)
{
    int n = 0;
    do
    {
        n = get_int("Please type in an integer here: ");
    }
    while ( n < 0 || n > 23);
    {
        printf("%i\n", n);
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .