How to effect a return of a value from the _calling_ function?

Viewed 221

I would like to be able to force a 'double-return', i.e. to have a function which forces a return from its calling function (yes, I know there isn't always a real calling function etc.) Obviously I expect to be able to do this by manipulating the stack, and I assume it's possible at least in some non-portable machine-language way. The question is whether this can be done relatively cleanly and portably.

To give a concrete piece of code to fill in, I want to write the function

void foo(int x) {
    /* magic */
}

so that the following function

int bar(int x) {
    foo(x);
    /* long computation here */
    return 0;
}

returns, say, 1; and the long computation is not performed. Assume that foo() can assume it is only ever called by a function with bar's signature, i.e. an int(int) (and thus specifically knows what its caller return type is).

Notes:

  • Please do not lecture me about how this is bad practice, I'm asking out of curiosity.
  • The calling function (in the example, bar()) must not be modified. It will not be aware of what the called function is up to. (Again in the example, only the /* magic */ bit can be modified).
  • If it helps, you may assume no inlining is taking place (an unrealistic assumption perhaps).
4 Answers
Related