3 ms·
I use a few strategies instead of goto: (1) For simpler cases, wrap in do {} while (0) and break from the loop (2) For multiple cleanups, use same technique c
by cjensen 2y ago
I use a few strategies instead of goto:
(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.
- dktoao 2y ago`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.
- armitron 2y ago35 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.
- John_Cena 2y agoWould 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.
- throw16180339 2y agoHow 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.
- cjensen 2y agoObviously first two strats don't work, so I would use the third.