Vishal said:
i m new to the C world...
i ve been told by my instructors not to use goto stmt..
but no one could give me a satisfactory answer as to why it is so..
plz help me out of this dilemma, coz i use a lot of goto in my codes....
Bad structured code is orders of magnitude easier to debug and maintain
than bad unstructured code.
You shouldn't need to use goto very often. One problem with using goto
is that it can destroy the ability to debug code by inspection. It's
not so much the goto itself that's the problem, but rather than the
uncertainty introduced in the code around the target of the goto. For
instance, given the code fragment:
i = 7;
label: printf("%d\n", i);
What value gets printed for any particular path of execution? Until I
account for every instance of "goto label;", I don't know. I have to
trace all possible paths of execution before I can say with any
confidence what gets printed under what conditions. This makes code
harder to debug and maintain. God forbid I have to make any changes,
because I can't say with any confidence that any change will not
inadvertantly affect *some* path of execution.
The story I like to tell is one program I stumbled across early in my
career written by an electrical engineer. A 5000-line main() function,
with something 15 gotos, some of which branched forward, some backward.
It took my co-worker two full weeks to figure out how the damn thing
actually worked. We were tasked with improving performance of the app,
but anything we did simply broke the code. We finally recommended that
the customer just buy faster hardware; it would be cheaper than the
effort to make the code faster would cost.
Now, that particular application was pathological beyond the use of
gotos, but they made a bad situation impossible. Had the code been
somewhat structured, we probably could have made some improvements.
Gotos are useful in a limited set of circumstances, like when you need
to break out of a deeply nested loop, or need to make sure some cleanup
code runs before exiting a routine. But they should not replace
control structures like if-else , for, while, do-while, or switch
statements.
If you're going to use a goto, make sure you branch forward *only*, and
that you do not branch into a block.