Monday, May 24, 2010

Why is goto in programming frowned upon?

Being a hobby programmer (c++ and any other language I feel like learning) I have read from numerous source that using the


goto keyword is a bad thing and should be avoided.





From what I've read it is avoided because it basically makes your code hard to read/understand, but I think that if used properly it can be usefull.





I also dabble in assembly, and was getting confused with the jmp until I learned about the goto and then it hit me....





jmp is almost exact to goto.





So wouldn't goto help people who want to learn oh say assembly??





I have also found goto helpfull in rare cases.





what about you??

Why is goto in programming frowned upon?
A program statement is like a sentence. It can be direct. It can also be long and rambling, taking you from the court of Saladin the Magnificent to H. P. Lovecraft's dinner table where you will learn he detested fish.





I have no doubt you have found gotos useful. C has a statement called break, which gets you out of whatever loop or switch statement you hapen to be in. There are certainly cases where they are called for. Generally, though, they are so useful in redirecting program actions that they can give you a scope as broad as my sentence with Saladin and Lovecraft. And it makes it very easy to forget that happens after the sentence is complete. The program can hang or terminate without accomplishing its original purpose.





If you expect to be the person maintaining this code until it's finished or the Messiah comes, fine. If not then you are well advised to think of others and plot things from the top down so you do leave the most direct and uncluttered sentences for them to look at you can.





%26lt;/tongue in cheek %26gt;
Reply:Using goto does make you code harder to follow and opens up the possibility that another person that modifies the code will make a mistake. If it wasn't for the use of gosub it might be alright. If one uses a goto after a gosub and before the return then you can imagine how confusing it could become.





If there are several gosubs within gosubs then it gets even worse.


Time is money and all the employers I have worked for do not like spending money on spaghetti code problems.





Top down and modular, that's the ticket


No comments:

Post a Comment