Undeclared Identifier in do while loop, C
The scope of the variable height
is the body of the do
..while
loop. The condition of this loop is outside of the body, therefore height
is not in scope in the loop condition.
Move the definition of height
outside of the loop.
int height;
do
{
//ask for input with 1-8
height = get_int("Height: ");
}
while (height > 0);
Height is not visible (nor exists) after the closing brace of the do
body block. You must declare it outside of the loop. I've marked the points where height
ceases to exist in comments below:
int main(void)
{
do
{
//ask for input with 1-8
int height = get_int("Height: ");
} // <- the scope and visibility of height ends here
while (height > 0); // ... so it doesn't exist here.
}
the solution is to declare height
before the do
keyword, as in:
int main(void)
{
int height;
do
{
//ask for input with 1-8
height = get_int("Height: ");
}
while (height > 0); // now, height is visible here.
} // <-- visibility and scope of height ends here.
Another thing is that, if your intention is to ask for a height and repeat the question until height > 0
, then you should write while (height <= 0)
instead, (you repeat the question while the answer is not correct)