9 ms·
some of possible reasons to use goto: 1. escape nested loops easily for () ... for() ... if (something) goto get_me_out .
by iExploder 5y ago
some of possible reasons to use goto:
1. escape nested loops easily
for ()
...
for()
...
if (something)
goto get_me_out
...
get_me_out:
2. error handling; since c does it in somehow messy way, you can end up with multiple variations of:
if (error)
close
return
if (error)
deallocate;
close;
return
where by using goto you can put those handlers as in a footnote of a function like
if (error)
goto error1
if (error)
goto error2
error2:
deallocate
error1
close
as it looks a bit neater
some languages like Zig for example have keyword defer, this to my understanding implements an alternative to this approach
- AnimalMuppet 5y agoNote, however, that if you have multiple different cleanup-and-exit points, it can be a maintenance issue. (On the other hand, the non-goto version can also be a maintenance issue...)