This question is a duplicate of Goto Still Considered Harmful. If you wish to discuss this further please use the original question.
Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.
-
I think its a detriment to readability, personally.
-
It encourages bad coding style, basically. See: Goto Considered Harmful [pdf]
-
It means you haven't designed the code procedurally.
If you build your whiles and ifs properly, you should rarely ever need goto.
Rarely is the key word. There are times where it's useful. In that sense, many people nowadays just explicitly throw and catch exceptions, just to avoid the dreaded goto.
-
It can rapidly lead to spaghetti code.
-
GOTO short circuits your control flow, thereby undermining your design and opening the door to debug and maintenance nightmares.
Matthew Whited : They are also short circuit your control flow allowing for easier movement without pointless if, functions, or loops leading to less code to maintain and debug. -
Note that Djkstra wrote "GOTO Considered Harmful", not "GOTO Considered Deadly". It has its places. Unfortunately, the judgement to know when to use it comes after you've got some experience in maintaining other people's code, especially code that was written years ago by people who no longer work in your company. Thus, it's best to avoid goto as much as you can until you have that experience.
-
Edgar Dijkstra wrote an excellent paper about this topic. You can read the paper here.
-
Readability becomes a problem, and flow of logic can have unintended effects by the use of goto.
I think its funny that the .net compiler will change some case/switch statements to use goto.
-
In some cases it makes sense. But, in the majority of cases use of it it considered poor practice because it can make the execution path of code tricky to read compared to using structured code such as for loops and while loops.
When you look at a goto or a label, you don't really know where is goes to or comes from without reading or searching through the code for the label name. This is tricky especially if the goto doesn't fit on the same screen as the label. Compare this to a for loop or a while loop or an if.. you can tell from the structure (i.e. indenting of the code) what the execution path is.
Having said this, it sometimes is useful, especially for example when jumping out of some nested for loops that are digging for a particular value inside a multi-dimensional array. You could use a goto here to jump out of the for loops when the correct value is found.
-
Because the structure of the code can be difficult to follow.
This
y: // do more stuff goto x p: // do stuff // then done goto y; x: // do a bunch of stuff if (...) goto y; else goto p; done:
is much less clear than
int main() { x(); } function p() { if (...) { return; } } function x() { if (...) { return; } else { p(); } }
0 comments:
Post a Comment