Symbian_Curator

Symbian_Curator t1_iycacc6 wrote

I just want to point out, GOTO is not completely pointless, but the industry is used to repeating how GOTO is terrible without thinking much about the reasons, the reasons being as you pointed out, but also, valid uses for GOTO are so few and far between that it's just easier to teach new programmers to simply never use it.

About those valid uses:

  • In C, to mimic the destructor behaviour of C++ in function. For example, let's say that in function F you have: initialize resource A, initialize resource B, initialize resource C, do some work, clean u C, clean up B, clean up A. Then, in the code, you would try to init A, and if it works, carry on, but if not, exit the function. Try to init B, and if it works, carry on, but if not, GOTO "clean up A" part. Try to init C, and if it works, carry on, but if not, GOTO "clean up B" part. When you GOTO like this, the code "falls through" to clean up only the resources which were initialized. I was told that this technique is used widely in the code of the Linux kernel, but honestly I haven't bothered to check myself.
  • With some compiler extensions, computed GOTOs (where you can take the address of a GOTO label, put it in a lookup table, and jump based on some index) present a optimization opportunity for performance critical code, notably interpreters for other languages or bytecode of other languages. (it's similar to switch/case, just faster)
11