News for hackers. Stuff that matters.
Re:C: Simple Defer, Ready to Use by cjensen on Monday January 06, 2025 @02:49PM (#42614792)
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.

Re:C: Simple Defer, Ready to Use by dktoao on Monday January 06, 2025 @04:39PM (#42616205)
`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.
Re:C: Simple Defer, Ready to Use by armitron on Monday January 06, 2025 @04:53PM (#42616384)
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.

Re:C: Simple Defer, Ready to Use by John_Cena on Monday January 06, 2025 @08:59PM (#42618370)
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.
Re:C: Simple Defer, Ready to Use by cjensen on Tuesday January 07, 2025 @01:03PM (#42625324)
Obviously first two strats don't work, so I would use the third.