10 print “bad code”; 20 goto 10;

Twice this week, I have used ‘goto’ because any other way would mean loads of code just to jump the control from one point of my program to another point in a big mess of nested loops. Traditionally while we were learning programming, everyone taught us GOTO and they have also advised us against it. But why ?

I know the code becomes slightly unreadable, but anything beyond that ? Why were we all taught not to use goto ? OK the code *will* look messy if I had more then 10 goto statements, but what if I use 2 – 3 of them instead of writing ~200+ lines of code ?

45 Comments

  1. zimbabao · August 27, 2004 Reply

    .. i have seen some of the widely used code using goto to jump at the resource releasing and at one place return statements block, everytime an error is occured .. So u can use it safely .. till atleast u understand ur code 😉

  2. zimbabao · August 27, 2004 Reply

    me with my friend wrote an article abt how we can use goto from better way, from our experienece ..

  3. vibhanshu · August 27, 2004 Reply

    most people advise u against without even realizing why they are doing so.

    A GOTO stmt is an equivalent of the a JMP being made in assembly code. (Check out the diassembly view of ur code sumtime). This is exactly what happens when u make a function call, tho the handling of the stack (pushing operands on the stack, cleaning it up and all after the function returns) is handled by the callee or the caller, depending on how u compile the program ( _cdecl etc… ) Now when u make a GOTO none of this stack handling is taken care of. So once u make a jump it might be impossible for u to clean up stuff urself, becoz things have gone out of scope and all.

    Baseline, using GOTO is a good enuf practise if u know what ur code does and u have taken care of everything. No memory leaks and all. And YES lot of good programs do use GOTO, like my dear PS RIP 😉

  4. premshree · August 27, 2004 Reply

    Are you the same Kalyan we all know? Dude, you should have known better than to ask such a question.

    There’s always a tradeoff between programmer efficiency and program efficiency. Sure, the Towers of Hanoi problem could be solved more efficiently using GOTOs, but it would be prettier if solved using recursion.

  5. anomalizer · August 27, 2004 Reply

    I’m GW BASIC programmer. goto was the only way to do any sort of branching 🙂
    On a more serious note, the inability to jump multilevels from a nested loop is a pain without goto.
    If u’re making sure that ur goto target is the start/end of a block and ur using it to bail out ouf a a very deep loop, its ok. Otherwise its bad.

    If i every get my hands on my GW BASIC code that I wrote (like how many years ago, umm lemme see 9 years ago I think), I’ll show u why goto is messy

  6. gromhellscream · August 27, 2004 Reply

    show the code..most probably there’s a way not to use goto’s. Goto’s are best avoided..You always add one here thinking that you will never add another..but it tends not to be the last one…

  7. yathin · August 27, 2004 Reply

    http://www.acm.org/classics/oct95/

    There are a lot of work arounds for goto – from simple ‘if’ to using dynamic polymorphism! 😉

  8. yathin · August 27, 2004 Reply

    forgotten ‘gosub’?

  9. yathin · August 27, 2004 Reply

    Nopes, recursion can cause stack-overflows. GOTO will not.

    So, what do you choose beauty or efficiency? 😉

  10. admin · August 27, 2004 Reply

    When did recursion become pretty ? Infact I would anyday advice a person to use goto over recursion.

  11. admin · August 27, 2004 Reply

    I would think twice about using goto in a C program. I was using perl and memory leaks are not too much of an issue there. Also my use of goto is to jump out of couple of nested if’s and for’s and nothing more.. I am not jumping all over the program 😉

    Thanks for post… just the stuff I was looking for.

  12. zimbabao · August 27, 2004 Reply

    “Now when u make a GOTO none of this stack handling is taken care of. So once u make a jump it might be impossible for u to clean up stuff urself, becoz things have gone out of scope and all.”

    u can’t jump across a function so i dont think this is valid . and reopurce leak is only possible is it needs a explicit release .. like connection or dynamically allocated memory .. correct me iff wrong

  13. admin · August 27, 2004 Reply

    but what do you do if you are buried in 3 nested if’s and 2 for loops ? Maybe someone should come up with an argument for ‘break’ so you can specify how far do you want to break

  14. admin · August 27, 2004 Reply

    I would be an idiot to jump from one nested loop/if to another one.

    I just need to break to be honest and I used goto so that I can just jump to later part of the program where I do something totally unrelated.

    You want to see messy code ? just check rr’s code 😉

  15. anomalizer · August 27, 2004 Reply

    I consider that as branching too. Just yesterday i was telling about the joy of goto,gosub,peek,poke etc

  16. shoan · August 27, 2004 Reply

    PHP already has this 🙂

  17. yathin · August 27, 2004 Reply

    If you use Perl:
    use last

  18. admin · August 27, 2004 Reply

    Nice

    No wonder all versions of PHP < v5.0 do not have goto support ;)

  19. yathin · August 27, 2004 Reply

    Just when I was getting kicks out of gotos and gosubs, I moved to QBasic – which had functions, subroutines and user defined types as well. 😀

    So, I’m not too much of a GWBasic programmer.

  20. bluesmoon · August 27, 2004 Reply

    dude, if you’re using perl, then you should use the last LABEL and next LABEL constructs to jump out of multiple loops/go to the next iteration of an outer loop. eg:

    LOOP1: for(....)
           {
    LOOP2:    for(...)
              {
    LOOP3:        for(...)
                  {
                      next LOOP2 if $something;
                      last LOOP1 unless $that_thing;
                      redo LOOP2 if $bad_read;
                  }
              }
           }

    Why most profs tell you not to use goto – their profs told them so, and they never did think about it.

    Where did the thought come from? Beginners to programming wouldn’t know how to use goto correctly. They almost always have 1000 line functions (as just mentioned) and then gotos become unreadable.

    OTOH, as says, if you want to handle errors within a function similar to how VB does it (On Error Goto ErrorHandler), do it this way:

    int foo()
    {
        if(!do_something)
           goto error;
    
        if(!do_something_else)
           goto error;
    
        return 0;
    
    error:
        log_error;
        return -1;
    }
  21. bluesmoon · August 27, 2004 Reply

    you can’t return from a GOTO, you can from a GOSUB.

  22. bluesmoon · August 27, 2004 Reply

    perl always had that 🙂

  23. premshree · August 27, 2004 Reply

    Exactly my point. I never said recursions are more efficient, but they make programmer sense.

    So, what do you choose beauty or efficiency? 😉
    It really depends. If efficiency is not of prime concern, I’d choose beauty.

    Tell me, would you prefer coding the solution to Towers of Hanoi recursively … or using GOTOs?

  24. yathin · August 27, 2004 Reply

    Recursion of course! 😉

  25. code_martial · August 27, 2004 Reply

    Nah. Recursion is sweet. Try iteration/GOTOs for tree traversal, for example.

  26. code_martial · August 27, 2004 Reply

    Another thing is that if you have a loop that goes three levels deep, you’re doing something pretty significant out there. Dedicate a function call to the loop and to break out of the loop, just return.

  27. bluesmoon · August 27, 2004 Reply

    Not always possible, especially when you need to modify several variables across all three loops. In many cases, yeah, you can.

    Would you still make it a function if it were two loops?

  28. bluesmoon · August 27, 2004 Reply

    divide and conquer is always beautiful

  29. code_martial · August 27, 2004 Reply

    Two loops can be handled easily by a flag.

  30. bluesmoon · August 27, 2004 Reply

    The moment you introduce flags, your code becomes ugly. When you perform tasks (manually, or in your mind) you don’t maintain flags to break out of multiple loops, you just say, break out to that loop.

  31. vibhanshu · August 27, 2004 Reply

    u cant jump across functions but there can be many scopes within a functions (well i am talking mostly of c, but all other programming languages would follow i guess).

    And when i said maintainence I did mean dynamic memory allocation and all.

    Well logically u can do anything using GOTO that u can use functions, u just need to figure out how to pass the parameters. Even recursion dude 😀 Just need to figure out how ur gonna structure ur code. At the assembley level its just a stack and couple of registers that do all the computation.

    and if u just want to break from a for loop this would be the neatest way instead of using flags and other means. Tho u need to review u code to ensure that u do not screw up anything in between.

  32. zimbabao · August 27, 2004 Reply

    .. my point is u can use u can use goto io release the resources in cleaner way rather then cluttering the code , ..

  33. appaji · August 27, 2004 Reply

    A link for a link

    http://www.azillionmonkeys.com/qed/goto.html

    Hehe, a link for a link 😉

  34. aivalli · August 27, 2004 Reply

    Ok ! Fine now the 34th comment has been posted !

    I’d like to add that – I was taught ro **avoid** goto and not that I **must not** use it.

    Also, if things were so bad then R & K might have as well dropped it from the C lang ! 😉

    Probably, they too went thru the same situations as ! 🙂

    HTH.

    -nerdy

  35. bipin · August 27, 2004 Reply

    > but what if I use 2 – 3 of them instead of writing ~200+ lines of code
    That’s where the problem lies. ~200 lines to rid yourself of a goto or two, and you’re pretty sure you’ve already got yourself some screwed up code.

    Goto, generally, is discouraged *as a looping mechanism*. So doing this:

    label:
    	++i;
    	// do something
    	if (i > 10) goto label;
    

    is not wrong but totally gross. Breaking out of loops perhaps, is a place where a goto would be acceptable, though, as pointed out, a cleaner version of break

    Somewhere along the line of posts, jumping out of if statements came about. I’m assuming this:

    
    	if ()	{
    		// do something
    
    		if () goto label; // jump
    
    		// do something else
    	}
    label:
    

    instead, you could try:

    	if ()	{
    		// do something
    		if (!)	{
    			// do something else
    		}
    	}
    

    Couldn’t think of a place where your jump doesn’t boil down to this sequence.

    Forgive me, but i *always* prefer programming elegance and algorithmic efficiency to code efficiency. Leave that bit to an intelligent compiler. It’ll probably do more than you’d ever can.

    *checks his shield for strength*

  36. bipin · August 27, 2004 Reply

    > Nopes, recursion can cause stack-overflows. GOTO will not
    Wrong. Bad programming causes stack-overflows, not recursion :p

  37. yathin · August 27, 2004 Reply

    I said recursion can cause stack overflows! 😉

  38. ravi · August 27, 2004 Reply

    Minor english nitpicks

    Hey.

    a cleaner version of break is supported by Java et all.

    First of, I think you mean “et al“, not “et all

    Secondly, as it says on the Wikipedia page:

    Et alii (et al.)
    "And others" — used to abbreviate a list of names (Alii is actually masculine, so it can be used for men, or mixed men and women; the feminine et aliae is appropriate when the "others" are all female.)

    ‘et al’ is reserved for people! So you could say, “ram, shyam, et al” but not “buses, cars, et al” … so unless ‘Java’ is the name of a person that hangs in a prominent group, your usage is wrong …

  39. bipin · August 27, 2004 Reply

    Re: Minor english nitpicks

    >First of, I think you mean “et al”, not “et all”
    Sorry .. i got that wrong. Damn you auto spell-check.

    As for the second bit, i am aware of it’s relation to people. Excuse my nerdiness in believing in software elements ruling my life. What with ‘servers’ and ‘clients’ and ‘editors’ 🙂

  40. bipin · August 27, 2004 Reply

    Re: Minor english nitpicks

    >First of
    I think you mean “first off“, not “first of”

    sorry, couldn’t help myself 🙂

  41. themadman · August 27, 2004 Reply

    Wow, the nerd convention is in town!

    (former nerd)

  42. admin · August 28, 2004 Reply

    heh.. I was expecting religious replies.. not C++ template ones 😀

    but hey… watch it buddy.. some people still have to do this for living.

  43. cadbury · August 28, 2004 Reply

    tis all right

    it might sound ironic, but sometimes, in certain cases,
    having gotos can actually make your code more readable!
    To paraphrase :
    http://old.tpu.org/tea/Thread2./cg-29/id-1405
    “Goto is nothing but a tool.Use it wisely and it can provide great power (like a chainsaw). Use it foolish and suffer greatly (do I need to say more?)”

  44. Anonymous · December 12, 2004 Reply

    Why not GOTO

    This is covered in Djkstra’s (sp?) paper “GOTOs considered harmful”.

    The core idea is that by purely using gotos, you end up writing spaghetti code, which is hard to maintain. He suggested breaking the code into logical blocks instead and exiting out of each block appropriately.

    The use of gotos is not harmful, excessive use is.

Leave a Reply