Why does a recursed return call break out of stack without an explicit return statement?

后端 未结 4 1764
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 15:10

I was shown a sample program to demonstrate recursion which looks like it should not work but does. The logic is pretty clear but why does it work even when the recursed fu

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 15:19

    I can explain exactly what happens:

    The function is called, and it recurses back into itself until it reaches the return at either modulo (return 0) or end of recursion (return 1). At this point the function reuturns to the caller, which is is_prime. But there is no more code in the function to execute, so it immediately returns without any further action.

    However, you could easily break this by, for example, add printf("Done for %d, %d\n", num, i); behind the call of is_prime() [doesn't have to be in the if-statement]. Or adding a C++ object that is created and destroyed on entry/exit of the function, as another example.

    You're just being lucky that it works. And it's very fragile and easy to break - compile it with a different compiler (or with different optimization settings, or a new version of the compiler, or a million other things), and it may well break.

提交回复
热议问题