The magic function calls itself recursively in two places. So in each of those places, you need to check your exit condition. The answer given by paddy details this.
An alternative for immediate unwinding of the stack is to use setjmp and longjmp which can function as a non-local goto.
jmp_buf magic_buf; void magic_int(char* str, int i, int changesLeft) { if (changesLeft == 0) { printf("%s\n", str); if (voices(str)) { longjmp(magic_buf, 1); } return; } if (i < 0) return; // flip current bit str[i] = str[i] == '0' ? '1' : '0'; magic_int(str, i-1, changesLeft-1); // or don't flip it (flip it again to undo) str[i] = str[i] == '0' ? '1' : '0'; magic_int(str, i-1, changesLeft); } void magic(char* str, int i, int changesLeft) { if (!setjmp(magic_buf)) { magic(str, i, changesLeft); } }
The setjmp function returns 0 when called directly. When longjmp is called, it is the setjmp function that actually returns, and the return value is the second parameter given to longjmp.
Here, we have a wrapper function which calls setjmp. This sets the jump point for when longjmp is called. Then the recursive function is called. Later, when the recursive function "hears voices" telling it to quit now, it calls longjmp which immediately goes directly to the corresponding setjmp call.
These functions are specified in C99 as well as POSIX, so a POSIX conforming system (i.e. Linux) should still have these available in C89 mode.
If you were to do this in C++, the preferred method would be to throw an exception in the recursive function and catch it in the wrapper function.
struct magic_voices { int rval; }; void magic_int(char* str, int i, int changesLeft) { if (changesLeft == 0) { printf("%s\n", str); int rval = voices(str); if (rval) { struct magic_voices ex; ex.rval = rval; throw ex; } return; } if (i < 0) return; // flip current bit str[i] = str[i] == '0' ? '1' : '0'; magic_int(str, i-1, changesLeft-1); // or don't flip it (flip it again to undo) str[i] = str[i] == '0' ? '1' : '0'; magic_int(str, i-1, changesLeft); } void magic(char* str, int i, int changesLeft) { try { magic(str, i, changesLeft); } catch (struct magic_voices ex) { printf("rval=%d\n", ex.rval); } }