Monday, May 16, 2011

Goto vs. Higher-level control structures

Some very simple programming languages allow you to control the flow of your program with the goto keyword. You simply place a label somewhere in your program, and then can can jump to that point in your code anytime you like by following goto with that keyword. Like so:

goto myLabel
...
myLabel:
/* code */

In these simple and limited programming languages, goto may be used quite commonly, and this feature is included in C/C++ too. It is however, considered extremely bad practice.

The reason for this is simply that there are better alternatives. C and C++ provide more advanced control structures like various types of functions and loops, which not only make it easy to code a certain behavior, but safer. goto is still sometimes used for customized control, like breaking out of heavily nested loops.

It has been said that if your program does indeed require the use of goto, you should probably be redesigning the whole program to fix it properly instead of using a quick fix like goto.

If in doubt, don't use goto