undeclared variable in a do-while loop in C

103 views Asked by At

I want to use a variable that i receive from the user to further frame a condition in a loop.

do
{
    int sp= get_int("Enter the start size of llama population:");

}
while (sp>=9);

how shall i fix this error? i am new to C

I wanted the sp variable to receive an input greater or equal to 9, and if not, i wanted to prompt the user again to enter a valid number with the help of a do-while loop. however, this resulted in an undeclared variable error.

2

There are 2 answers

0
Clifford On

sp is out of scope after the closing brace of the {...} block it is declared in. You need to declare it in the same scope as the while statement:

int sp = 0 ;
do
{
    sp = get_int("Enter the start size of llama population:");
}
while (sp>=9);
0
Harith On

Unless they are VLA, automatic variables have a lifetime — outside of which they can't be accessed — corresponding to the execution of their block of definition. Referring to an object outside of its lifetime has undefined behaviour.

Move the declaration of sp before the while construct.