`the do {} while (0)` block with breaks does exactly what goto does but it is so much more hacky, less flexible and harder to follow IMHO.
35 years of coding C don't amount to much if you ignore best practices. Look at the Linux kernel to learn how gotos can be used to make the code safer and improve clarity.
There's probably something wrong if a substantial project in C does NOT use gotos.
Would any particular piece of the kernel stand out to you in this manner? Last time I looked I didn't think too much about it being used.
Re:C: Simple Defer, Ready to Use
by throw16180339 on Monday January 06, 2025 @09:14PM
(#42618430)
How do you handle breaking out of a nested for loop without goto?
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.
(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.