0

I'm working on Pset1 and I keep getting an 'unused variable' error in my do/while loop. This is my code-

 int main(void)
 { 
     printf("How much change is owed?\n");
     float fcents = GetFloat()*100.0;

     if (fcents<=0)
     {
     do
     {
         printf("How much change is owed?");
         float fcents = GetFloat()*100.0;
     }
     while(fcents<=0);

     }


     int icents = (int) round(fcents);
     printf("integer cents: %d \n", icents);
}

I'm using the variable in the 'while' so the loop should run again. Ive checked the syntax many times and it looks right to me. What am I missing? Thanks!

2

Well, you're not actually using the variable that's declared inside of the loop, but we'll get to that. Here is a couple of points

  1. Every loop has a continuation condition (the one between the parentheses after while in this case). As long as this condition is true, the loop will continue executing. The do...while loop is special in the sense that it always executes at least once before checking its condition. The point is that I don't think you need to surround your loop with a condition because it already has one and you want its body to get executed at least once in this case.

  2. When you use a variable, you don't write its data type again. You just use its name directly.

    float f; // create f
    f = 10.5; // initialize f
    printf("%.1f\n", f); // print f
    

    You write a variable's data type when you create it though. Since you wrote the data type of your fcents variable inside the body of the loop, this is considered as creating another variable with the same name that shadows the original one that's outside of the loop and goes out of scope as the loop ends execution. That's why the compiler thinks that you're not using the variable named fcents that's declared inside the loop (because all you're doing is creating and initializing it).

| improve this answer | |
  • Yes, thank you Kareem! This finally cleared up at least 50% of the problems I've had with scope for the past 2 weeks. Ah, the relief. – Bradley Stone Mar 13 '15 at 4:20

You must log in to answer this question.

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