• Glen

Arrrrrrggghhhhh, the devil be in me, for the first time in 20 years, I used a



Arrrrrrggghhhhh, the devil be in me, for the first time in 20 years, I used a goto statement

Is it ok to use a goto statement? Vote at LinkedIn Poll: https://lnkd.in/gYeEgXxn

Yip, thats right, I have done the coding dirty deed and used a goto in C

Yet I am not embarrassed, in fact, I was finding myself far more embarrassed by the code that was otherwise evolving without that sinful goto.

You see, the function completed around 20 actions, and each of those actions had to be checked for error, and if an error had occurred, clean up and before returning that error.

The cleanup itself required up to 12 lines of otherwise repeated code like:

====

res=errno;

if ( fpassed)

pthread_mutex_unlock(&(ds_attrslck[fx]));

else

close(fx);

if ( fxrep ) close(fxrep);

if (fxe) close (fxe);

if (fxerep) close (fxerep);

if ( path != NULL ) free ( path);

if (depath != NULL ) free ( depath);

errno=res;

return -errno;

====


That would be over 200 lines of the same code repeated after each action.


Of course, I could have added 20 odd levels of if { ! err} before proceeding to the next action, but ok boy, that would have also made it a complex bit of code to follow.

So that smack on the hand, go home and think about what you have done - goto at the end of the function removed over 200 lines of near repeating code, that goto make the code far more straightforward to follow.


It is a win-win.


In short, sorry language-coding professor from many years ago.

While I generally do believe that goto statements should be avoided and avoiding gotos can force the developer to create much more thoughtful, more innovative and cleaner code, there are times (although few) when a goto statement is the right way to go.




43 views0 comments

Recent Posts

See All