Replacing goto

Sorry if this has already been asked, but I need to do away with a goto jump in my code.

Here's the section affected:

while(analogRead(ANALOG_PIN) < H_THRESH) {
    //wait until above high thresh, watch time
    if(millis() - time >= TIMEOUT) {
      debug("U");
      goto timeout;
    }
  } 
  while(analogRead(ANALOG_PIN) > L_THRESH) {
    //wait for low threshold
  }

  //some code
  timeout:
  //some more code

Any ideas? This is for a clapper, and I'm using the goto to handle timeouts.

Thanks a lot!

baum

All that the goto in that code is doing is getting out of the while loop and skipping the next while statement.

You could set a boolean to true before the first while, set it to false after the debug() call, and break; out of the while statement.

Perform the second while loop only if the flag is true.

bool doStepTwo = true;
while(analogRead(ANALOG_PIN) < H_THRESH)
{ // Put the curly brace on a new line where it belongs
  //wait until above high thresh, watch time
  if(millis() - time >= TIMEOUT)
  {
    debug("U");
    doStepTwo = false;
    break;
  }
}

if(doStepTwo)
{
  while(analogRead(ANALOG_PIN) > L_THRESH)
  {
    //wait for low threshold
  }
  //some code
}
  //some more code

Thanks!

Also... why are goto statements bad?

baum

Well there's a hole with no bottom. Would you settle for "It's unrestricted use makes your code harder to follow & thus harder to debug"? If not, google "goto statement considered harmful" and you should find enough commentary and other links to keep you busy for hours.

Also... why are goto statements bad?

It breaks the semantics of fundamental building blocks especially

  • the repetition
  • the procedure call

You might get stack and heap pollution (especially in the last).

Please read the article mentioned by wildbill, it is an eyeopener

Please read the article mentioned by wildbill, it is an eyeopener

which one?

Dijkstra's. Here's one link to a copy of it: Go To Statement Considered Harmful

baum:
why are goto statements bad?

As far as this forum goes, I would say delay() has caused more confusion, agony and needless work than any amount of bad goto-programming.

for delay:

why not simplify it to something like BlinkWithoutDelay? We can, ofcourse, keep delay()as delayNoInterrupts() or something like that.

it should be noted that delay() is really just a "noob" tool. It makes getting started with Arduino easier. The coder will eventually discover the limitations of delay(). If they come from basic-land, however, they may have some bad habits regarding the use of goto that should be un-learned. Goto is actually harder to use in C, so at least the coder "gets a clue".