0

Hi I'm getting an error that says "x" is an unused variable. And I'm also getting errors every time I try to use "x". I have reviewed David's get_int example from Lecture 1:

    int main(void)
    {
        int i = get_int("Integer: ");
        printf("hello %i\n", i);
    }

I don't see how what I'm doing is very different, besides the bit about creating new variables s and h. (I tried this because putting those equations directly in the print instructions wouldn't let it run either.)

Any feedback appreciated -- thank you for looking!

Here also is my full code in case that's helpful.

    #include <cs50.h>
    #include <stdio.h>

    int main(void)
    {
    do
    {
        int x = get_int("Height of half-pyramid: ");
    }
    while (x<0 || x>23);

    int s = x-1
    int h = i+1

    for(i=1; i<= x; i++)
    {
        printf("%s*' '", s);        /*prints x-1 spaces*/
        printf("%h*'#'\n", h);      /*prints i+1 hashtags*/
    };
    }

mario.c error messages

1

It's an issue called variable scope, something that will be explained later. Simply put, a variable only exists within the surrounding pair of curly braces where it is created.

In Prof. Malan's example, the variables are created inside the curly braces that contain all of main(). In your case, x only exists inside the do/while loop and is destroyed when the code exits the loop.

The errors are explained like this. The unused variable error happens because x is not used again inside the do/while loop where it exists. After the do/while loop, since x no longer exists, each time the code tries to use it, a "variable doesn't exist" error is generated.

If you simply declare the variable before the do loop, int x; the problem should go away.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |
  • Thank you Cliff, noted. I think I followed your instructions correctly, but still getting an issue with it. imgur.com/Q4xicR6 – EB Gold Sep 9 '18 at 18:25
  • I have a similar variable problem on my cash.c program. I moved the variable up above the do loop but something still not right w/ the variable... – EB Gold Sep 9 '18 at 19:30
  • Sounds like a new question needs to be posted. – Cliff B Sep 10 '18 at 1:21

You must log in to answer this question.

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