Invoking return through a function?

Chris Angelico rosuav at gmail.com
Mon Oct 30 23:34:31 EDT 2017


On Tue, Oct 31, 2017 at 2:00 PM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> Python has no GOTO, fortunately, but C has at least two, GOTO and LONGJMP. A C
> macro could, if I understand correctly, jump into the middle of another
> function. (Yay for spaghetti code!)

No, I don't think you do understand them correctly - or at least, I
don't know of any way for a C macro to jump into the middle of a
function.

There are three quite different things mentioned here.

1) The 'goto' statement, which unconditionally jumps you to another
location *in the same function*
2) setjmp/longjmp, which is not actually a "goto", but more of a
"multi-level return"
3) Preprocessor macros, which expand to some form of C source code.

Since macros have to expand to legal C code, they can't do anything
that you couldn't do by simply writing out the code - they just hide
it behind a token that looks like a function call. To use
setjmp/longjmp (which, btw, are actually standard library functions,
not language features) to jump into another function, you first have
to call the destination; they're much more akin to exception handling
than to an unstructured 'goto' (in fact, they're often used in the
implementation of exception handling). Basically, longjmp can only
rewind you to a previous setjmp, and only if the function that called
setjmp has *not returned* - so you can only use it to jump outwards,
not inwards.

But feel free to point out something I've forgotten, wherein you can
actually jump into the middle of a function using a macro. There's
enough dark corners in C that it's entirely possible I've missed
something obvious.

ChrisA



More information about the Python-list mailing list