Shop OBEX P1 Docs P2 Docs Learn Events
To GOTO or Not to GOTO? — Parallax Forums

To GOTO or Not to GOTO?

ercoerco Posts: 20,261
edited 2011-11-10 18:15 in General Discussion
Here's an interesting debate (disclaimer: in another forum for another uC) on how the GOTO command is ruining programmers and should forever be abolished from all programming languages. I had no idea that the issue was so polarizing! Me, I love GOTOs and all they stand for.

http://www.picaxeforum.co.uk/showthread.php?19737-When-to-use-Goto-and-not-Do-While-Until&p=185934&viewfull=1#post185934

The argument goes way back to 1968: Edsger Dijkstra's 1968 article, "Go To Statement Considered Harmful": http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html
«13

Comments

  • TinkersALotTinkersALot Posts: 535
    edited 2011-11-03 16:08
    some people are so prone to short-jumps-to-conclusions :)

    my vote: goto's are okay if used with "good taste"
  • prof_brainoprof_braino Posts: 4,313
    edited 2011-11-03 16:09
    I agree with Dijkstra. I've seen many clever and cute uses of goto, and clever and cute do not go too well with engineering projects that require input from more than one person. The result quickly becomes unmaintainable. Better is the realization that if you have resort to "tricks" to get "just a bit more" out of the system, its time to refactor and find something that does not need cute tricks.

    Of course if the project is a single person effort and the goal is to queeze as much juice a possible, then any trick is fair game. As long as "mamagement" doesn't hand it over to the B-team with new set of features to add...
  • rod1963rod1963 Posts: 752
    edited 2011-11-03 16:32
    I agree with Dijkstra as well, it's not needed. But if it just code for a personal project where no one else is gonna see the source, it's a different story.
  • ercoerco Posts: 20,261
    edited 2011-11-03 16:48
    I defend my use of plywood, relays, and GOTOs. One of favorite code-crunching tricks is this:

    a:if in1=0 then a (yes, there's an implied GOTO in there)

    which obviously waits and loops forever as long as in1 remains low, and skips & proceeds when in goes high. Here, the implied GOTO is a concise & powerful way to check a pin, especially useful for BS1 users (who would use PIN1 instead of in1, natch) who are trying to cram as much as possible into 256 bytes.

    In a marginally related story, I just located the dusty videotape of the very first Trinity Firefighting Robot contest in 1994, where my code-crunched, GOTO-bloated BS-1 controlled robot won first prize. I'll Youtube it once I find my dusty VCR and digitize it.
  • Martin_HMartin_H Posts: 4,051
    edited 2011-11-03 17:51
    At the assembly level they're obviously unavoidable in the form of a jmp instruction. But in a well designed higher level language they are unnecessary. The only place I used them in C was for invoking a common function exit handler on an error. The introduction of try, catch, finally into Java and C# made a that use unnecessary.

    Erco, in C that a: if then a would be a while loop. You need it only because PBASIC is not fully block structured. Spin would use some variant of the repeat construction.
  • bsnutbsnut Posts: 521
    edited 2011-11-04 01:28
    I use the GOTO command when I am working with Basic Stamp 1 mostly. Because it is hard not to use it. But, for those who are new to programming will use it due to the fact easy to use.

    I don't use the GOTO command when I am programming in a higher level languages like Spin and writing code for the BS2. The reason is, that I don't need to label my program to death for each IF..THEN statement that I have.
  • TorTor Posts: 2,010
    edited 2011-11-04 03:07
    Martin_H wrote: »
    The only place I used them in C was for invoking a common function exit handler on an error.
    That's the only place I've used them as well in general code. Never needed them anywhere else.
    The introduction of try, catch, finally into Java and C# made a that use unnecessary.
    Yep, if C had something like that the goto to a common exit handler wouldn't be needed.
    Another thing is that by refactoring the C code to something which both looks and maintains better the need of that goto typically goes away too (the only reason to use it is of course that the alternatives would have looked worse).

    When that's been said, what Dijkstra was talking about was 'goto' in a certain context, afaik. Anyway, my C programs don't need it, usually. I just looked through some code and the only place I could find it was in a state machine I once wrote as an automatic instruction test generator for an emulator.

    -Tor
  • GadgetmanGadgetman Posts: 2,436
    edited 2011-11-04 03:27
    There's a very simple rule about GOTO, and that is that it shouldn't end further than halt a printed page away. If you need it to skip more code than that, there's probably something REALLY bad in your code.
    In fact, using a GOTO probably means you've used done something wrong, flow-control wise anyhow.

    Using GOTO is like turning to the Dark side; Used once and you can never RETURN..

    As for 'OK for home use'...
    No...
    Always code to the BEST of your abilities, not the worst. Always write the code as if it is a big project at work and that it will be read/modified/supported by other programmers in the future.
    This is because it takes less than two months for you to forget what 'that clever little bit of code' did...
  • Heater.Heater. Posts: 21,230
    edited 2011-11-04 03:46
    The goto is a wonderful thing.
    Thank God C does not have exception handling. The goto as a means of aborting on error is much nicer.
    There are nearly 93000 gotos in the Linux 3.1 kernel sources. Linux is huge, has a huge number of developers, is quite reliable and is progressing nicely so I guess goto is not so harmful.

    In my professional career I have only used goto once. Oddly that was for a military project where there were very strict standards to follow and all code was reviewed at least once by the quality control guys. They did not like it. I had to get it specially approved and signed off. It was there for performance reasons in an interrupt handler.

    goto is especially nice if you can hide it in a macro where no one can see it. Over on the gcc alpha test thread I have a full duplex serial UART implemented in C and compiled to raw PASM in a cog. It uses coroutines rather like the original PASM FDS transmit and receive threads. Using goto there means you can actually get up to 115200 baud using C. All the task switching gotos are neatly hidden in macros.
  • LoopyBytelooseLoopyByteloose Posts: 12,537
    edited 2011-11-04 06:01
    This is the good old 'spaghetti code' debate. There is nothing wrong with GOTOs in their pure state, it is how the user uses or abuses them. The simple fact is that Assembly language has a generic equivalent in the Jump mnemonic. So if it were really possible to do away with, the Assemby op code would never have a Jump. That is not very realistic.

    In sum, GOTO is okay; Spaghetti Code is NOT okay. Make your code readable and people will appreciate what you have done. Make it impossible to read and you will have to debug and recode alone.

    Just consider this, if you cannot write good clear and concise prose, why do you think you can write excellent software? Writing is both about good organization and an understanding of what your audience really can follow.
  • Heater.Heater. Posts: 21,230
    edited 2011-11-04 06:35
    Loopy,

    Quite so.

    GCC also provides for "super gotos". A non standard extension to C called "labels as values". So given a function with some labels in it, lab1: lab2: lab3: etc one can write:

    void* labelValue;
    labelValue = &&lab2;
    goto labelValue;

    Clearly with this one can get goto to go to just about anywhere with potentially interesting results. You can build arrays of label values and use them as jump tables. All sorts of fun.
    Anyway, that is what I used in my full duplex serial threads.
  • stamptrolstamptrol Posts: 1,731
    edited 2011-11-04 07:04
    I'm with the plywood, relay and GOTO users on this.

    Having to date myself almost back to the 1968 reference, the GOTO issue was not so much about the command itself but the ensuing spagettified result, which has been pointed out.

    As can be seen over the years, any language can be twisted into a labyrinth of unmaintainable, unfathomable result, regardless of whether GOTOs are available or not.

    The lack of clear thought and planning can allow spagetti code to develop regardless of the construct. Even today, in training industry folks to do control programming, the concept of taking the time to use the ideas of flowcharting to ensure a clear understanding of the problem before the first line of code is written is still emphasized.

    Its the same argument that goes to those programmers who feel compelled to use each "cute" bit of code or obscure contruct to demonstrate their wizardry.

    Said many years ago, the adage that "If simplicity is the crown of genius, complexity is the cloak of mediocrity" is especially true of programming.

    Cheers,
  • rod1963rod1963 Posts: 752
    edited 2011-11-04 09:19
    I'll say this the people whom I saw use GOTO's badly were sloppy BASIC coders whose code was close to unreadable. Where I saw GOTO's being used intelligently and sparingly were among DoD Fortran-77 coders, whose code was the most readable I've ever come across outside of some ADA and Oberon code. But these programmers were also expected by management to write code in a manner that it could be read and maintained by others.

    Can you write without GOTO? Yes, even OS's.

    Personally I've never had to use it outside of coding on the ancient BS2, which thankfully I haven't had to touch in a decade.
  • Roy ElthamRoy Eltham Posts: 3,000
    edited 2011-11-04 09:35
    People that argue against using goto don't seem realize that the code they write to avoid it is just hiding the goto. In the resultant assembly output, the while loop (or whatever choice you use) is going to look the same as if you used a couple of labals and goto statements.

    Avoiding a part of the language just because it can be abused to make bad code is silly. If you use that argument against goto, then you should stop using most of the language, because it can all be abused to make bad code.
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2011-11-04 09:55
    Roy, I think you're confusing structure with behavior. Although programs written in highly-structured goto-less languages can produce the same behavior as programs with gotos, that's really beside the point. Not allowing gotos forces the programmer to abstract away from the jumps produced by the compiler in the resulting object code and think more hierarchically. That's really the point of a high-level language, isn't it? And it's a Good Thing, too, since fewer bugs are produced, those that do sneak in are easier to isolate, and the code's readability is enhanced.

    Obviously, a good programmer can write structured code using gotos, But that's also beside the point. None of us started out as good programmers. I would contend that those fortunate enough to cut their teeth on goto-less languages became good programmers more quickly than did those who were given gotos from the get-go. I was in that latter group, and it was a struggle to shift gears when introduced to a goto-less language. But doing so forced me to think about programming in ways that have made me much more productive in the years since. I'm sure I'm not alone in that regard.

    -Phil
  • ratronicratronic Posts: 1,451
    edited 2011-11-04 12:25
    I'm going to get there goto or not!
  • 4x5n4x5n Posts: 745
    edited 2011-11-04 14:00
    Roy Eltham wrote: »
    People that argue against using goto don't seem realize that the code they write to avoid it is just hiding the goto. In the resultant assembly output, the while loop (or whatever choice you use) is going to look the same as if you used a couple of labals and goto statements.

    Avoiding a part of the language just because it can be abused to make bad code is silly. If you use that argument against goto, then you should stop using most of the language, because it can all be abused to make bad code.

    Some of the worst code I've ever tried to make sense out of didn't use a single goto!!
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2011-11-04 14:09
    I don't think there's any disagreement that good programs can be written with gotos and that bad programs can be written without them. That's not news. On the whole, though, I contend that reliability, readability, and serviceability favor a structured programming discipline that lacks gotos. Moreover, if you program yourself into a corner that "requires" a goto, it's time to rethink the overall structure of your code.

    -Phil
  • localrogerlocalroger Posts: 3,452
    edited 2011-11-04 17:29
    I firmly believe Djikstra was trolling. Knuth didn't agree with him, and the whole "considered harmful" thing was eventually banned from some publications because it was so inflammatory.

    The biggest legitimate use of GOTO is for critical failure handling in otherwise structured code. When you see really bad structured code with loops nested 13 deep it's often because the poor sod writing the code couldn't or didn't want to use GOTO to eject from some process that was fatally hung. TRY/CATCH and Spin's ABORT only partially fix this because sometimes you want to respond to a failure in different ways depending on what the failure is. Banning GOTO trades potential complexity and spaghettiness in the mainline code for complexity and spaghettiness in error handling.

    Djikstra was a purist who worked on code in an environment where he did not have to worry about erroneous operator inputs, failed sensors, and timeouts. In embedded apps GOTO can be very useful for simplifying logic and making it MORE readable. The same thing holds for things like data scope; data hiding is all very well and good until an error handler needs access to that inconveniently hidden data to clean up some mess that wasn't supposed to happen. Spin can be maddening in this regard.

    Phil does make a good point that the enforced discipline can make you a better programmer, but let us not kid ourselves that it universally makes for better programs. There comes a time to take the training wheels off of our bicycles, and if we leave them on we are never going to dream of winning the Tour de France.
  • Martin_HMartin_H Posts: 4,051
    edited 2011-11-04 17:36
    The real question is can C-INTERCAL's COMEFROM statement be useful in any of way?
  • 4x5n4x5n Posts: 745
    edited 2011-11-04 17:48
    I don't think there's any disagreement that good programs can be written with gotos and that bad programs can be written without them. That's not news. On the whole, though, I contend that reliability, readability, and serviceability favor a structured programming discipline that lacks gotos. Moreover, if you program yourself into a corner that "requires" a goto, it's time to rethink the overall structure of your code.

    -Phil

    It's been a long time since I found myself needing to use a goto outside of assembly or the basic that I used with my coco (radio shack color computer) and forget how to use them with C or Perl. To my knowledge Spin doesn't even have a goto!

    That said I don't think that the goto is a bad thing or causes "bad code". I do however agree with schools enforcing a ban on the goto! The reason is that I think if forces discipline on students that makes them better programmers in the long run.
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2011-11-04 17:49
    localroger wrote:
    I firmly believe Djikstra was trolling. Knuth didn't agree with him, ...
    If MIX was his answer, obviously not! :) Ugh!

    -Phil
  • localrogerlocalroger Posts: 3,452
    edited 2011-11-04 19:22
    Knuth meant MIX to be a real-world environent.
  • PJAllenPJAllen Banned Posts: 5,065
    edited 2011-11-04 19:32
    erco,
    I need two to GOTO, please.
    (Oh, yeah, hey -- I'm in a hurry. OK? Thanks, man.)
  • LoopyBytelooseLoopyByteloose Posts: 12,537
    edited 2011-11-04 19:41
    Phil seems to be with the 'goto-less crowd' and justifies the by his own code preferences.

    What we really have is a range of computer languages from those that are very close to the hardware (Assembler, C, and such) to those that are very close to the user required task (Python, Java, and OOP in general)

    Sure, if you have really well-written and highly abstracted language in hand, you may completely avoid GOTOs. But you may have to avoid many of the low-level languages to do so.

    I've made by case by pointing out the OP CODE has the JMP command. If you have a small microcontroller with limited amounts of space, there may come a point that the JMP is quite necessary to get everything into the firmware.

    Of course, if you have unlimited computer space and unlimited processing speed - you can be stylistic and wax eloquent about your programing philosophy.
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2011-11-04 19:51
    [quote=Loopy Byteloose[/quote]I've made by case by pointing out the OP CODE has the JMP command. If you have a small microcontroller with limited amounts of space, there may come a point that the JMP is quite necessary to get everything into the firmware.[/quote]
    Nearly every assembler has a JMP command -- or several. That's how high-level constructs like if/then, do/while, etc. get implemented in a compiler's object code. We're not discussing assemblers, though, but gotos in high-level languages.

    -Phil
  • Heater.Heater. Posts: 21,230
    edited 2011-11-04 21:59
    The fact that there is a JMP instruction in the hardware is irrelevent to whether we have a goto in our high level languages or not. The prop does not have a multiply but Spin does. The Prop does not support a stack natively but C compilers make their own and Forth is a stack based language.

    One point about goto not mentioned here so far is about proving the correctness of your code. In some circles they attempt to prove that a code meets it spec mathematically. These methods don't work in the face of goto.
  • LoopyBytelooseLoopyByteloose Posts: 12,537
    edited 2011-11-04 21:59
    High level versus low level is rather an over-simplification. There is a range and it is not easy to line up all languages on one line. PBasic is relatively low level due to what if provides and the nature of the platform. It accommodates a GOTO which the compiler likely converts directly to a token that uses a JMP. Microsoft's version of Basic is extremely high level and abstracted at this point.

    I did mention that we have a rather diverse range of programing languages at this time - more than ever before. The really high level ones, tend to focus on programing as TASKS from a library of objects; whereas the other extreme is very bound to OP CODE of a particular silicon chip. If you just stay at one end of the range, it is easy to assert generalizations.

    But the closer you are to the hardware, the more you have to accommodate its physical structure. Having a Subroutine that spans across Pages in the SX chip is a good example. It is best not done as the Program Counter gets off into the weeds; so instead of just having code sequentially arranged, one might jump across a Page boundary and back again.

    Furthermore, there is more than one way to be modular and clear. Some people use GOTO statements to clarify something and it doesn't have a hardware restriction, but is a handy stylistic device. I suspect that is why PBASIC provided it.
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2011-11-04 22:26
    Early versions of PBASIC did not have the language structures enjoyed by the current 2.5 version, so GOTO was a necessary evil. I suspect that GOTO exists in 2.5 only for backwards compatibility, not as an essential -- or at this point, desirable -- element of the language.

    -Phil
  • Rick_HRick_H Posts: 116
    edited 2011-11-04 22:50
    I am an anti-Authoritarian by nature and its this kind of blank check statement that is primarily the reason why. I started programing on a TI with GWBasic and I don't even think its possible without millions of if statements to do anything useful in a language like that old as it may be.
    Bad coding is bad coding but sometimes elegance can be over average peoples heads. I am primarily a PLC programer now and the last job I did the project manager told me not to use latching bits because in his eyes they where harmful. I wrote the code any way in a state logic fashion. basically it was a conveyer system that had to pass a part from cell to cell with handshaking and retain data specific to that part. Each cell needed to be able to receive a part simultaneously receiving a part if their was one waiting and then when the part it was sending was received buy the next cell it would perform certain ops on the part. I did each cell in less than 14 rungs of code with latching bits. it worked flawlessly, but when the project manger found out that I used latching bits he freaked out and rewrote the code. His code could not request a part while sending a part so the system was slow and his code required 32 rungs of logic per cell. Later on the customer requested my code because his code was not power dropout safe and they would loose data from their SCADA system. In all reality the only reason he didn't like latching bits is because he didn't under stand how to implement them properly.
Sign In or Register to comment.