I've been staring at my computer for so long trying little tweeks to fix the error message. TLDR how do I stop the shadow message from appearing and initialize variable h? The image looks confusing since I print screened after changing int h to int n but did't check correctness until after, see int n as int h. No matter what I do the message is the same. I've changed the variable from h to n like the example thinking that it was my choice in a random letter h that was the problem. I made int n and left my variable as h. I'm so confused now, this is my first time coding but I'm frustrated. Please help me, it is greatly appreciated. Blanked out some of the code for honor code reasons.
1 Answer
It's a scope issue. The variable "h" is created inside the curly braces, so it ceases to exist after the closing brace, where it is tested. In other words, h only exists between the curly braces on lines 10 and 12. You can't do it that way if you plan to use h outside of those curly braces.
Instead, create h before starting the loop so that it persists through the remaining code where you need it. int h;
before the 'do' statement. And since you're going to set the contents of h immediately (inside the loop), there's no need to initialize it.
FYI, a variable will only exist between the nearest opening curly brace before it and the matching closing brace that follows. That's the "scope" of it's existence.
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)
-
I had int h before and it said the same thing. I know the image says int n but that is because I was in the process of changing h's to n's. It seems like there is some other problem with it.– Rayray94Commented May 1, 2020 at 18:29
-
-
But I don't know how to fix it. It's saying declaration shadows a local variable now when I type make mario.– Rayray94Commented May 1, 2020 at 19:11
-
That's exactly what I expected. A shadow variable occurs when you redeclare a variable. My bet is that when you try to use the variable, you're also using the
int
declaration with it. So, remove the laterint
. If this isn't it, you will need to post the current code so I can see exactly what you're doing. Also, search the forum for "shadow variable" for more info and understanding.– Cliff BCommented May 1, 2020 at 19:24 -