22 ms·
In vanilla C, exceptions do not exist. Thus goto is the standard (at least for the Linux kernel) statement for handling exceptions.
by Tideflat 10y ago
In vanilla C, exceptions do not exist. Thus goto is the standard (at least for the Linux kernel) statement for handling exceptions.
- carterehsmith 10y agoOh, I see. Is that something like setjmp/longjmp?
- unwind 10y agoNo, 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-kernel-programmers-use-goto-instead-of-simple-while-loops http://stackoverflow.com/questions/13001067/why-do-some-kern... and https://www.kernel.org/doc/Documentation/CodingStyle https://www.kernel.org/doc/Documentation/CodingStyle (chapter 7 but that's raw text so I can't link).
- marrs 10y agoI 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.
- marrs 10y agoLet 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)
- carterehsmith 10y agoOK, then. The OP mentioned "previously gained value instantly disappears". I do not see what exactly disappears with GOTO?