int get_cents(void)
{
do
{
int i = get_int("How many cents customer is owed?: ");
} while (i < 0);
return i;
}
I am beginner and i am stuck at this problem and getting error >use of undeclared identifier
CodePudding user response:
You have to check the scope of variables in c. Keeping it simple, a variable is visible inside the {}
where it has been declared, so in your case the variable i
does not exists outside the loop. A correct solution for your code is:
int get_cents(void)
{
int i;
do
{
i = get_int("How many cents customer is owed?: ");
} while (i < 0);
return i;
}
CodePudding user response:
In C, variables have a scope. Means the variables have a limit of till where can it be used... The scope of any variable is only till the closing brace of the compound body it was written in. For eg:
if(true){
int x = 999;
}
x ;
This operation cannot be performed since x is declared inside the compound body of if()
block so it's using limit is only till the if()
block... Even if you do not put braces, the block remains the same so still you will get an error... This is what I mean...
if(true)
int x = 999;
x ;
Even though there is no braces {}
used but still this code will give you output since again, x
is declared within the if()
block and is used outside it...
So in your program, just you are declaring variable i
inside the do...while()
loop so it cannot be used at the condition of the do...while()
loop since that is considered as out of the do...while()
block. So this is what should you write then...
int get_cents(void)
{
int i;
do
{
i = get_int("How many cents customer is owed?: ");
} while (i < 0);
return i;
}