Hacker News new | ask | show | jobs
by Tideflat 3537 days ago
In vanilla C, exceptions do not exist. Thus goto is the standard (at least for the Linux kernel) statement for handling exceptions.
1 comments

Oh, I see. Is that something like setjmp/longjmp?
No, it's just plain goto, to a named label which is (for this case) later in the function.

It's quite common in low-level code where you want to do a bunch of things that can all fail, and you need to rewind and undo the things that succeeded up to the point of failure.

See http://stackoverflow.com/questions/13001067/why-do-some-kern... and https://www.kernel.org/doc/Documentation/CodingStyle (chapter 7 but that's raw text so I can't link).

I wrote a simple set of c/++ macros to encapsulate this functionality, though it still relies on the dev to unwind in the correct order

#define HANDLE_ERROR(label) bool label = false; #define ENSURE(label, pred) if (!(pred)) { label = true; goto label; } #define RESOLVE(label) label: if (label)

HANDLE_ERROR statements go at the beginning of the block, RESOLVEs go at the end, in the reverse order to the ENSUREs, which go wherever they're required.

It's been working well for me so far.

Let me try that again with formatting this time:

    #define HANDLE_ERROR(label) bool label = false;
    #define ENSURE(label, pred) if (!(pred)) { label = true; goto label; }
    #define RESOLVE(label) label: if (label)
OK, then.

The OP mentioned "previously gained value instantly disappears". I do not see what exactly disappears with GOTO?