Hi,
I want to know why people say that we should not use goto statement?
What are the problems with it I find it easy to turn the flow of my program with just a single line in C?
Please explain!
Hi,
I want to know why people say that we should not use goto statement?
What are the problems with it I find it easy to turn the flow of my program with just a single line in C?
Please explain!
I do know the "good uses" of 'goto'. However, I have never found myself needing to use it. I have found, however, that usually the alternative clean solution to using goto is better encapsulation. The thing is that the "good use" of 'goto' often deals with resource management/freeing, and I have found that encapsulation is a much safer and cleaner way for resource handling, and a good implementation actually makes the code better, safer and more reusable.
Just as a very small example to visualize what I mean: When you handle C-style "strings" (ie. dynamically allocated char arrays) in a function, you constantly need to be very careful to free everything you have allocated at each exit point of the function.
Because it's tedious to write all the same freeing calls at each exit point, 'goto' is sometimes used to jump to the end of the function where everything is freed. However, compare that to using std::string in C++: You don't have to worry about freeing them because they will be automatically freed when the function is exited. You don't need to use 'goto'. At the same time the function becomes cleaner, easier to read and, most importantly, *safer*.
And no, I'm not saying that's the only "good use" of 'goto'. I just wrote one example of what I'm talking about.
However, it's generally accepted that using goto every now and then to brake out of multiple nested loops is better than creating flags and adding checks to the conditions.
If you're a beginner, though, it's better if you avoid it. At least until you create some criteria of when to use it and when not to use it.
I seem to recall being called a horrible, talentless coder (or something similar) when I argued that there might be a reason to use gotos. Specifically, case statements used for state machine code, but whatever.
Of course, the fact that calling foo(x) is, for all practical purposes, a GOTO (really a GOSUB) is just a bit too 'deep' for some people.
http://www.cprogramming.com/tutorial/goto.html
Bookmarks