Friday, July 5, 2013

A 'proper' use of GOTO

Ever since Knuth criticized goto people have been spouting that GOTO is the worst language construct to ever use.


I'm fairly sure that 80% of them have never used a GOTO statement in their life, nor understand why sometimes it is the most logical thing to do.
For example here is an example:
  It really is logical here and I'll tell you why. Lets look at what I'm doing here in pseudo form:


read in a character:

 read in the next character

  Does this match a comment statement?

    Eat the input until the end of the comment

  No? Then just output it and keep going


Now you might be asking me, why didn't you write it with functions and fully modularize your code and encapsulate all the functionality? Simple. This is an exercise from a book. It is mean to be a simple one script that handles a low level functionality of removing comments. It's code is simple and it doesn't benefit from encapsulation (A point that's arguable but only if you're playing devils advocate)

Also, even using functions and all that to encapsulate each portion isn't going to save you the real trouble here unless you place the second while loop into the function. Now why do I have to use goto here? People unfamiliar with scoping rules should be aware that your instinct to throw a continue statement in in order to skip out of the loop will only skip the current block scope you're in. In other words, a continue in the second while will not break you out of the first while like you need to in order for this algorithm to work. A goto statement ignores scope since it's an unconditional branch.

Let the haters commence:
You might ask me, well obviously that scoping thing makes sense, but the program can be rewritten with functions to be clearer. In which case I'd tell you that Occam's razor holds true for small one off programs like this.

But, just to convince you that the use of goto is a "neccesary evil".  Take a look here I don't know about you, but I trust the kernel programmers. Considering they wrote your operating system, your drivers, and all the things that make your shiny web applications run smoothly.

No comments:

Post a Comment