Go Down

Topic: Whats up with GOTO command? (Read 9 times) previous topic - next topic

Ray Andrews

GOTO is evil, plain and simple  >:(

Seriously though you can always write code better without it. You should see your LED sequences as separate functions, not just locations further down in the program. Anything you 'need' to GOTO should probably be a function.

This could be simplified more, but it integrates with what you've already written if you change the goto labels to proper functions

Code: [Select]

void loop()
{
 int buttonval = 0;
 
 if (digitalRead(SW1) == LOW) buttonval += 1;
 if (digitalRead(SW2) == LOW) buttonval += 2;
 if (digitalRead(SW3) == LOW) buttonval += 4;
 buttonval += 1;

 switch (buttonval)
   {
   case 1 : LED_1();  break;
   case 2 : LED_2();  break;
   case 3 : LED_3();  break;
   case 4 : LED_4();  break;
   case 5 : LED_5();  break;
   case 6 : LED_6();  break;
   case 7 : LED_7();  break;
   case 8 : LED_8();  break;
   }
}

AznCaleb

Wow that makes way more sense, I was reading up on functions and how they are used but I guess it didn't really make sense to me, I tried to use them in this program too but I messed up with the syntax so I just used goto. Thanks for all the help!

crimony

Quote
GOTO is evil, plain and simple


Not true.

Quote
Seriously though you can always write code better without it.


Also not true, and it depends on what you mean by "better". If by "better" you mean any of "more readable", "faster" or "more efficient" then there are many cases where *not* using goto will result in "worse" code.

There's a good discussion on this in the lkml (Linux kernel mailing list) archive from 2003. http://kerneltrap.org/node/553/2131

In this particular case, goto shouldn't be used, and it's initial use reflects the O.P.'s inexperience and that's fine, but making unilateral statements about a language feature that is useful in a small subset of problems is unhelpful. A better rule is "don't use goto unless you have exhausted all other language features and goto still looks better"

Ray Andrews

Quote
there are many cases where *not* using goto will result in "worse" code


Just for the sake of discussion (not trying to argue or anything) can you provide an example or two.  This is one of those topics that people love to fight about, but I just like to see how other people think.

RuggedCircuits

This is pretty much the only time I think it should be used (i.e., as a replacement for the structured exception handling in languages like C++/Java/Python/etc.):
Code: [Select]

int trysomething(void)
{
 char *buf = 0;
 success = 0;

 if (do_something() == 0) {
       print_error(1);
       goto fail;
 }

 buf = (char *)malloc(100);

 if (do_something_else() == 0) {
       print_error(2);
       goto fail;
 }

  ...

 success = 1;

fail:
 if (buf) free(buf);
 return success;
}

Go Up