Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>goto</code> is not inherently bad, it has it's uses, just like any other language feature. You can completely avoid using <code>goto</code>, by using <code>exceptions</code>, <code>try/catch</code>, and loops as well as appropriate <code>if/else</code> constructs.</p> <p>However, if you realize that you get extremly out of your way, just to avoid it, it might be an indiaction that it would be better to use it.</p> <p>Personally I use goto to implement functions with single entry and exit points, which makes the code much more readable. This is the only thing where I still find goto usefull and actually improves the structure and readabillity of the code.</p> <p>As an example:</p> <pre><code>int foo() { int fd1 = -1; int fd2 = -1; int fd3 = -1; fd1 = open(); if(fd1 == -1) goto Quit: fd2 = open(); if(fd2 == -1) goto Quit: fd3 = open(); if(fd3 == -1) goto Quit: ... do your stuff here ... Quit: if(fd1 != -1) closefile(); if(fd2 != -1) closefile(); if(fd3 != -1) closefile(); } </code></pre> <p>In C++ you find, that the need for such structures might be drastically reduced, if you properly implement classes which encapsulate access to resources. For example using smartpointer are such an example.</p> <p>In the above sample, you would implement/use a file class in C++, so that, when it gets destructed, the file handle is also closed. Using classes, also has the advantage that it will work when exceptions are thrown, because then the compiler ensures that all objects are properly destructed. So in C++ you should definitely use classes with destructors, to achieve this.</p> <p>When you want to code in C, you should consider that extra blocks also add additional complexity to the code, which in turn makes the code harder to understand and to control. I would prefer a well placed goto anytime over a series of artifical if/else clauses just to avoid it. And if you later have to revisit the code, you can still understand it, without following all the extra blocks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload