Home > Blockchain >  Undeclared Identifier in do while loop, C
Undeclared Identifier in do while loop, C

Time:01-16

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    do
    {
        //ask for input with 1-8
        int height = get_int("Height: ");
    }
    while (height > 0);
}

And I got the error code: use of undeclared identifier "height" (in the while statement) I'm completely green to programming and I have no idea how to fix this. Can someone help?

CodePudding user response:

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);

CodePudding user response:

The loop design is incorrect for what you wish to do. The correct thinking on this should be:

  1. Get a value
  2. If the value is zero, terminate the loop
  3. Else do stuff with the value

Hence:

while (true)
{
  int height = get_int("Height: ");
  if (!height) break;

  // use height here //
}

EDIT: By the way, in current versions of C you can integrate the variable into the loop condition:

while (int height = get_int("Height: "))
{
  // use height here //
}

I think this is true of C 11 or later, but it might have been introduced in C 14, IDK and don’t care to look it up. You should be using nothing less than C 17 these days...

  •  Tags:  
  • Related