by cjensen · 1y ago · 0 comments
(1) For simpler cases, wrap in do {} while (0) and break from the loop
(2) For multiple cleanups, use same technique combined with checks to see if the cleanup is required. E.g. if (f != null) fclose (f)
(3) put the rest of the stuff in another function so that the exit code must run on the way out.
In 35 years of coding C/C++, I've literally never resorted to goto. While convenient, this new defer command looks like the kind of accidental complexity that templates brought to C++. That is, it provides a simple feature meant to be solve simple problems in a simple way that accidentally allows architecture astronauts the ability to build elaborate footguns.
There's probably something wrong if a substantial project in C does NOT use gotos.
for (…) {
for (…) {
if (…) {
…
goto found;
}
}
}
found:
This is straightforward with goto and may even be vectorizable. I guess you could move the loop to a separate function or add additional flags to each loop, but neither of these seems like an improvement.